Merge pull request #8294 from dev-chirag/master

BAEL3455 Maximum Subarray problem
This commit is contained in:
Jonathan Cook 2019-12-15 16:08:03 +01:00 committed by GitHub
commit c5072b83f8
4 changed files with 107 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.maximumsubarray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BruteForceAlgorithm {
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
public int maxSubArray(int[] arr) {
int size = arr.length;
int maximumSubArraySum = Integer.MIN_VALUE;
int start = 0;
int end = 0;
for (int left = 0; left < size; left++) {
int runningWindowSum = 0;
for (int right = left; right < size; right++) {
runningWindowSum += arr[right];
if (runningWindowSum > maximumSubArraySum) {
maximumSubArraySum = runningWindowSum;
start = left;
end = right;
}
}
}
logger.info("Found Maximum Subarray between {} and {}", start, end);
return maximumSubArraySum;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.maximumsubarray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KadaneAlgorithm {
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
public int maxSubArraySum(int[] arr) {
int size = arr.length;
int start = 0;
int end = 0;
int maxSoFar = 0, maxEndingHere = 0;
for (int i = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = arr[i];
} else
maxEndingHere = maxEndingHere + arr[i];
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;
}
}
logger.info("Found Maximum Subarray between {} and {}", start, end);
return maxSoFar;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.algorithms.maximumsubarray;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BruteForceAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//given
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
//when
BruteForceAlgorithm algorithm = new BruteForceAlgorithm();
int maximumSum = algorithm.maxSubArray(arr);
//then
assertEquals(6, maximumSum);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.algorithms.maximumsubarray;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//given
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);
}
}