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

Commit 2b27f3a

Browse files
author
Ram swaroop
committed
largest sum contiguous sub array : comments added
1 parent dc1afa5 commit 2b27f3a

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,54 @@
1010
public class LargestSumContiguousSubArray {
1111

1212
/**
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+
*
1516
* @param a
1617
* @return
1718
*/
18-
public static int getLargestSumOfContiguousSubArray(int a[]) {
19+
public static int getLargestSumOfContiguousSubArray(int[] a) {
1920
int maxSum = 0, maxSumTillIndex = 0;
2021

2122
for (int i = 0; i < a.length; i++) {
2223
maxSumTillIndex += a[i];
2324
if (maxSumTillIndex < 0) {
2425
maxSumTillIndex = 0;
25-
}
26-
if (maxSumTillIndex > maxSum) {
26+
} else if (maxSumTillIndex > maxSum) {
2727
maxSum = maxSumTillIndex;
2828
}
2929
}
3030
return maxSum;
3131
}
3232

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+
3353
public static void main(String a[]) {
3454
System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4}));
3555
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}));
3762
}
3863
}

0 commit comments

Comments
 (0)