Maximum Subarray
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.Solution
class Solution {
public int maxSubArray(int[] nums) {
// 1.
// [1, -2] -> 0, 0 -> 1 > -... yes, max = 1, move end++, 0, 1 -> -1 > 1 no, so 1
// [-2, 1, -3-, 4], 0, 0 -> -2, 0, 1 -> -1 - start++, 1, 1 -> 1 yes, end++
// two pointers, start = 0; end = 0
// max sum = Integer.MIN_VALUE
// current sum = sum(nums, start, end)
// if (current > max) max = current
// else, increment end
int start = 0;
int end = 0;
int max = Integer.MIN_VALUE;
while(start < nums.length && end < nums.length) {
int sum = sum(nums, start, end);
if (sum > max) {
max = sum;
} else {
start++;
}
end++;
}
return max;
}
public int sum(int[] nums, int start, int end) {
int sum = nums[start];
int i = start + 1;
while (i <= end) {
sum += nums[i];
i++;
}
return sum;
}
}Last updated