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
.
一刷
题解:
初始设置结果为Integer.MIN_VALUE,然后当前curMax小于0时重置其为0。
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution {
public int maxSubArray(int[] nums) {
if(nums == null) return 0;
int max=Integer.MIN_VALUE, start =0, curSum = 0;
for(int i=0; i<nums.length; i++){
curSum +=nums[i];
max = Math.max(max, curSum);
if(curSum<0) curSum = 0;
}
return max;
}
}