File tree Expand file tree Collapse file tree 1 file changed +4
-7
lines changed Expand file tree Collapse file tree 1 file changed +4
-7
lines changed Original file line number Diff line number Diff line change 10
10
public class LargestSumContiguousSubArray {
11
11
12
12
/**
13
- * Based on Kadane's Algorithm. Doesn't work when all
13
+ * Based on Kadane's Algorithm. Doesn't work when all
14
14
* elements in array {@param a} are negative.
15
15
*
16
16
* @param a
@@ -31,19 +31,16 @@ public static int getLargestSumOfContiguousSubArray(int[] a) {
31
31
}
32
32
33
33
/**
34
- * TODO
34
+ * Below algorithm works even when all elements in array {@param a} are negative.
35
+ *
35
36
* @param a
36
37
* @return
37
38
*/
38
39
public static int getLargestSumOfContiguousSubArrayWhenAllNosNegative (int [] a ) {
39
40
int maxSum = a [0 ], maxSumTillIndex = a [0 ];
40
41
41
42
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 ]);
47
44
maxSum = Math .max (maxSum , maxSumTillIndex );
48
45
}
49
46
You can’t perform that action at this time.
0 commit comments