題目
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解決
解決思路:這是動態規劃的題目,突破口是要找到一個公式,使得dp[i] = x * dp[i-1] + y, 這樣子就可以根據上一個數推斷出下一個結果,達到O(n)解。
這裏的突破口是當前數nums[i], 是從自己開始,還是與前面的數dp[i-1] 加起來一起。這裏就要判斷dp[i - 1] > 0 ? dp[i - 1] : 0, 上一個數的和是否大於0.
那麼問題就迎刃而解了。
- 如果dp[i - 1] < 0, 就從自己開始 dp[i] = nums[i];
- 如果dp[i - 1] > 0, 就延續前任的記過 dp[i] = nums[i] + dp[i - 1];
- 如果最大數是歷史最大,則替換max = Math.max(max, dp[i]);, 最終結果爲max。
class Solution {
public int maxSubArray(int[] nums) {
// check edge
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException();
}
int length = nums.length;
int dp[] = new int[length];
dp[0] = nums[0];
int max = dp[0];
for (int i = 1; i < length; i++) {
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
}