1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
int singleLargest = Integer.MIN_VALUE;
int maxSum = 0;
int localSum = 0;
boolean sumStarted = false;
for(int i = 0; i < nums.length; i++){
singleLargest = Math.max(nums[i], singleLargest);
if (nums[i] >= 0){
sumStarted = true;
localSum = Math.max(localSum+nums[i], nums[i]);
maxSum = Math.max(localSum, maxSum);
}else if (sumStarted){
localSum += nums[i];
}
}
if (sumStarted){
return maxSum;
}
return singleLargest;
}
}
|
No comments:
Post a Comment