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.
public int maxSubArray(int[] A)
这一题代码写出来是很简单的,加起来七行不到。 这一题的算法其实也很直观,维护一个当前和,从头开始往后累加,只要还是正数就不停往下加,小于0就归零,过程里维护最大值。
public int maxSubArray(int[] A) {
int res = Integer.MIN_VALUE;
int cur_res = 0;
for(int i = 0; i < A.length; i++){
cur_res += A[i];
res = Math.max(cur_res, res);
cur_res = cur_res > 0 ? cur_res : 0;
}
return res;
}