Skip to content

Commit 4e95b34

Browse files
committed
fix the initial maxSum and add test
1 parent 989d295 commit 4e95b34

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithm.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,22 @@ public int maxSubArraySum(int[] arr) {
1313
int start = 0;
1414
int end = 0;
1515

16-
int maxSoFar = 0, maxEndingHere = 0;
17-
16+
int maxSoFar = arr[0], maxEndingHere = arr[0];
1817
for (int i = 0; i < size; i++) {
1918

2019
if (arr[i] > maxEndingHere + arr[i]) {
2120
start = i;
2221
maxEndingHere = arr[i];
23-
} else
22+
} else {
2423
maxEndingHere = maxEndingHere + arr[i];
24+
}
2525

2626
if (maxSoFar < maxEndingHere) {
2727
maxSoFar = maxEndingHere;
2828
end = i;
2929
}
3030
}
31-
logger.info("Found Maximum Subarray between {} and {}", start, end);
31+
logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
3232
return maxSoFar;
3333
}
3434
}

algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithmUnitTest.java

+12-1
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
99
@Test
1010
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
1111
//given
12-
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
12+
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
1313
//when
1414
KadaneAlgorithm algorithm = new KadaneAlgorithm();
1515
int maxSum = algorithm.maxSubArraySum(arr);
1616
//then
1717
assertEquals(6, maxSum);
1818
}
19+
20+
@Test
21+
void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
22+
//given
23+
int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 };
24+
//when
25+
KadaneAlgorithm algorithm = new KadaneAlgorithm();
26+
int maxSum = algorithm.maxSubArraySum(arr);
27+
//then
28+
assertEquals(-1, maxSum);
29+
}
1930
}

0 commit comments

Comments
 (0)