-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxSubarray.java
35 lines (29 loc) · 900 Bytes
/
MaxSubarray.java
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
27
28
29
30
31
32
33
34
35
public class MaxSubarray {
public static void main(String[] args) {
int nums[] = {5,4,-1,7,8};
System.out.println(maxSubArray(nums));
}
private static int maxSubArray(int[] nums) {
int max = nums[0];
int currentSum = nums[0];
int startIndex = 0;
int withoutStartIndex;
for(int i=1; i<nums.length; i++){
currentSum += nums[i];
if(nums[i] > currentSum){
currentSum = nums[i];
startIndex = i;
} else {
withoutStartIndex = currentSum - nums[startIndex];
if(withoutStartIndex > currentSum){
currentSum = withoutStartIndex;
startIndex += 1;
}
}
if(max < currentSum){
max = currentSum;
}
}
return max;
}
}