BAEL3455 Maximum Subarray Problem

This commit is contained in:
chirag d 2019-12-02 19:52:17 +05:30
parent 7807c24d2b
commit 9a8aadf125
4 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.subarray.maximum;
public class BruteForceAlgorithm {
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;
}
}
}
System.out.println("Found Maximum Subarray between " + start + " and " + end);
return maximumSubArraySum;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.subarray.maximum;
public class KadaneAlgorithm {
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;
}
}
System.out.println("Found Maximum Subarray between " + start + " and " + end);
return maxSoFar;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.subarray.maximum;
import org.junit.jupiter.api.Assertions;
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,23 @@
package com.baeldung.algorithms.subarray.maximum;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
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);
}
}