fix the initial maxSum and add test

This commit is contained in:
Kent@lhind.hp.g5 2021-03-14 22:28:23 +01:00
parent ce6f1e878e
commit 0290234485
2 changed files with 16 additions and 5 deletions

View File

@ -13,22 +13,22 @@ public class KadaneAlgorithm {
int start = 0; int start = 0;
int end = 0; int end = 0;
int maxSoFar = 0, maxEndingHere = 0; int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) { if (arr[i] > maxEndingHere + arr[i]) {
start = i; start = i;
maxEndingHere = arr[i]; maxEndingHere = arr[i];
} else } else {
maxEndingHere = maxEndingHere + arr[i]; maxEndingHere = maxEndingHere + arr[i];
}
if (maxSoFar < maxEndingHere) { if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere; maxSoFar = maxEndingHere;
end = i; end = i;
} }
} }
logger.info("Found Maximum Subarray between {} and {}", start, end); logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
return maxSoFar; return maxSoFar;
} }
} }

View File

@ -16,4 +16,15 @@ class KadaneAlgorithmUnitTest {
//then //then
assertEquals(6, maxSum); assertEquals(6, maxSum);
} }
@Test
void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(-1, maxSum);
}
} }