Maximum Subarray
lc 53
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.
twitter oa做过一道求target的最大subarray lc 325
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int res = Integer.MIN_VALUE;
int preMin = 0;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
res = Math.max(res, sum - preMin);
preMin = Math.min(preMin, sum);
}
return res;
}
}
public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int globalMax = nums[0];
int prevMax = nums[0];
for (int i = 1; i < nums.length; i++) {
prevMax = Math.max(prevMax + nums[i], nums[i]);
globalMax = Math.max(globalMax, prevMax);
}
return globalMax;
}
}