原题地址:https://oj.leetcode.com/problems/maximum-subarray/
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
经典的动态规划题,设 0 到 i 的连续字串最大和为sum[i],以 i 结束的连续子串最大和为 endSum[i],显然 sum[i] = max{endSum[i] + arr[i],sum[i - 1]},而 endSum[i] = max{endSum[i - 1], arr[i]}
public class Solution {
public int maxSubArray(int[] A) {
if (A == null || A.length < 1) {
return 0;
}
int endSum = Integer.MIN_VALUE;
int subSum = Integer.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
// update endSum
endSum = endSum > 0 ? endSum + A[i] : A[i];
subSum = endSum > subSum ? endSum : subSum;
}
return subSum;
}
}