Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathMaximumSubarray.java
More file actions
Latest commit
25 lines (20 loc) · 673 Bytes
/
Copy pathMaximumSubarray.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
packageproblems.medium;
/**
* Created by sherxon on 1/2/17.
*/
publicclassMaximumSubarray {
/**
* 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).
* */
publicintmaxSubArray(int[] a) {
if (a == null || a.length == 0) return0;
intmaxSoFar = a[0];
intmaxEndingHere = a[0];
for (inti = 1; i < a.length; i++) {
maxEndingHere = Math.max(maxEndingHere + a[i], a[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
returnmaxSoFar;
}
}