|
10 | 10 | public class LargestSumContiguousSubArray {
|
11 | 11 |
|
12 | 12 | /**
|
13 |
| - * Based on Kadane's Algorithm. |
14 |
| - * |
| 13 | + * Based on Kadane's Algorithm. Doesn't work when all |
| 14 | + * elements in array {@param a} are negative. |
| 15 | + * |
15 | 16 | * @param a
|
16 | 17 | * @return
|
17 | 18 | */
|
18 |
| - public static int getLargestSumOfContiguousSubArray(int a[]) { |
| 19 | + public static int getLargestSumOfContiguousSubArray(int[] a) { |
19 | 20 | int maxSum = 0, maxSumTillIndex = 0;
|
20 | 21 |
|
21 | 22 | for (int i = 0; i < a.length; i++) {
|
22 | 23 | maxSumTillIndex += a[i];
|
23 | 24 | if (maxSumTillIndex < 0) {
|
24 | 25 | maxSumTillIndex = 0;
|
25 |
| - } |
26 |
| - if (maxSumTillIndex > maxSum) { |
| 26 | + } else if (maxSumTillIndex > maxSum) { |
27 | 27 | maxSum = maxSumTillIndex;
|
28 | 28 | }
|
29 | 29 | }
|
30 | 30 | return maxSum;
|
31 | 31 | }
|
32 | 32 |
|
| 33 | + /** |
| 34 | + * TODO |
| 35 | + * @param a |
| 36 | + * @return |
| 37 | + */ |
| 38 | + public static int getLargestSumOfContiguousSubArrayWhenAllNosNegative(int[] a) { |
| 39 | + int maxSum = a[0], maxSumTillIndex = a[0]; |
| 40 | + |
| 41 | + 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 | + } |
| 47 | + maxSum = Math.max(maxSum, maxSumTillIndex); |
| 48 | + } |
| 49 | + |
| 50 | + return maxSum; |
| 51 | + } |
| 52 | + |
33 | 53 | public static void main(String a[]) {
|
34 | 54 | System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4}));
|
35 | 55 | 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 |
| 56 | + // kadane's algorithm doesn't work if all no.s are -ve |
| 57 | + System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, -1, -3, -4, -5, -1, -4})); |
| 58 | + |
| 59 | + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{-2, 1, -3, 4, 5, -1, 4})); |
| 60 | + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{2, -1, -3, 4, -5, 1, 4})); |
| 61 | + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{-2, -1, -3, -4, -5, -1, -4})); |
37 | 62 | }
|
38 | 63 | }
|
0 commit comments