题目
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;
}
}