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 end = 0;
int maxSoFar = 0, maxEndingHere = 0;
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = arr[i];
} else
} else {
maxEndingHere = maxEndingHere + arr[i];
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
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;
}
}

View File

@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//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
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
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);
}
}