Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit dc1afa5

Browse files
author
Ram swaroop
committed
largest sum contiguous sub array : done
1 parent 518e2af commit dc1afa5

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,30 @@
99
*/
1010
public class LargestSumContiguousSubArray {
1111

12-
public void largestSumContiguousSubArray(int a[]) {
12+
/**
13+
* Based on Kadane's Algorithm.
14+
*
15+
* @param a
16+
* @return
17+
*/
18+
public static int getLargestSumOfContiguousSubArray(int a[]) {
19+
int maxSum = 0, maxSumTillIndex = 0;
1320

21+
for (int i = 0; i < a.length; i++) {
22+
maxSumTillIndex += a[i];
23+
if (maxSumTillIndex < 0) {
24+
maxSumTillIndex = 0;
25+
}
26+
if (maxSumTillIndex > maxSum) {
27+
maxSum = maxSumTillIndex;
28+
}
29+
}
30+
return maxSum;
1431
}
1532

1633
public static void main(String a[]) {
17-
34+
System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4}));
35+
System.out.println(getLargestSumOfContiguousSubArray(new int[]{2, -1, -3, 4, -5, 1, 4}));
36+
System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, -1, -3, -4, -5, -1, -4})); // doesn't work
1837
}
1938
}

0 commit comments

Comments
 (0)