Java 19717 Potential issue in "Maximum Subarray Problem in Java" article (#14541)

This commit is contained in:
anuragkumawat 2023-08-25 15:39:06 +05:30 committed by GitHub
parent ed17162e4d
commit 63033cd8cf
2 changed files with 20 additions and 9 deletions

View File

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
public class KadaneAlgorithm {
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
private Logger logger = LoggerFactory.getLogger(KadaneAlgorithm.class.getName());
public int maxSubArraySum(int[] arr) {
@ -14,15 +14,15 @@ public class KadaneAlgorithm {
int end = 0;
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = maxEndingHere + arr[i];
if (arr[i] > maxEndingHere) {
maxEndingHere = arr[i];
} else {
maxEndingHere = maxEndingHere + arr[i];
if (maxSoFar < maxEndingHere) {
start = i;
}
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;

View File

@ -7,7 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
//when
@ -27,7 +27,7 @@ class KadaneAlgorithmUnitTest {
//then
assertEquals(-1, maxSum);
}
@Test
void givenArrayWithAllPosiitveNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
@ -39,4 +39,15 @@ class KadaneAlgorithmUnitTest {
assertEquals(10, maxSum);
}
@Test
void givenArrayToTestStartIndexWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { 1, 2, -1, 3, -6, -2 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(5, maxSum);
}
}