-
Notifications
You must be signed in to change notification settings - Fork 0
53. Maximum Subarray
Jacky Zhang edited this page Aug 28, 2016
·
1 revision
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.
解题思路为Dynamic Programming。
顺序扫描array,设置两个变量,一个记录到当前位置时的largest sum,一个记录以当前位置为终点的连续subarray的largest sum。
public class Solution {
public int maxSubArray(int[] nums) {
int maxSubArray = Integer.MIN_VALUE;
int maxEndHere = 0;
for(int num : nums) {
maxEndHere = Math.max(maxEndHere + num, num);
maxSubArray = Math.max(maxSubArray, maxEndHere);
}
return maxSubArray;
}
}