-
-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathMaximumSubarray.java
More file actions
25 lines (20 loc) · 673 Bytes
/
MaximumSubarray.java
File metadata and controls
25 lines (20 loc) · 673 Bytes
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
package problems.medium;
/**
* Created by sherxon on 1/2/17.
*/
public class MaximumSubarray {
/**
* We use two max, maxSoFar -> max sub array found so far and maxEndingHere -> maximum sub array size
* that ends in this index. This is in place solution and time Complexity is O(N).
* */
public int maxSubArray(int[] a) {
if (a == null || a.length == 0) return 0;
int maxSoFar = a[0];
int maxEndingHere = a[0];
for (int i = 1; i < a.length; i++) {
maxEndingHere = Math.max(maxEndingHere + a[i], a[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}