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

@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
@Test @Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() { void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//given //given
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5}; int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
//when //when
KadaneAlgorithm algorithm = new KadaneAlgorithm(); KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr); int maxSum = algorithm.maxSubArraySum(arr);
//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);
}
} }