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) {
if (A == null || A.length == 0)
return 0;
int local = A[0];
int global = A[0];
for (int i = 1; i < A.length; i++) {
local = Math.max(local + A[i], A[i]);
global = Math.max(local, global);
}
return global;
}