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

Commit 2a5c829

Browse files
author
Ram swaroop
committed
largest sum contiguous sub array : added method for all -ve no.s
1 parent aa73f79 commit 2a5c829

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
public class LargestSumContiguousSubArray {
1111

1212
/**
13-
* Based on Kadane's Algorithm. Doesn't work when all
13+
* Based on Kadane's Algorithm. Doesn't work when all
1414
* elements in array {@param a} are negative.
1515
*
1616
* @param a
@@ -31,19 +31,16 @@ public static int getLargestSumOfContiguousSubArray(int[] a) {
3131
}
3232

3333
/**
34-
* TODO
34+
* Below algorithm works even when all elements in array {@param a} are negative.
35+
*
3536
* @param a
3637
* @return
3738
*/
3839
public static int getLargestSumOfContiguousSubArrayWhenAllNosNegative(int[] a) {
3940
int maxSum = a[0], maxSumTillIndex = a[0];
4041

4142
for (int i = 1; i < a.length; i++) {
42-
if (a[i] > maxSumTillIndex) {
43-
maxSumTillIndex = a[i];
44-
} else if (maxSumTillIndex + a[i] < maxSumTillIndex) {
45-
maxSumTillIndex = a[i];
46-
}
43+
maxSumTillIndex = Math.max(a[i], maxSumTillIndex + a[i]);
4744
maxSum = Math.max(maxSum, maxSumTillIndex);
4845
}
4946

0 commit comments

Comments
 (0)