|
| 1 | +package com.thealgorithms.dynamicprogramming; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +public class KadaneAlgorithmTest { |
| 9 | + |
| 10 | + @Test |
| 11 | + void testMaxSumWithPositiveValues() { |
| 12 | + // Test with all positive numbers |
| 13 | + int[] input = {89, 56, 98, 123, 26, 75, 12, 40, 39, 68, 91}; |
| 14 | + int expectedMaxSum = 89 + 56 + 98 + 123 + 26 + 75 + 12 + 40 + 39 + 68 + 91; // sum of all elements |
| 15 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 16 | + } |
| 17 | + |
| 18 | + @Test |
| 19 | + void testMaxSumWithMixedValues() { |
| 20 | + // Test with mixed positive and negative numbers |
| 21 | + int[] input = {1, -2, 3, 4, -1, 2, 1, -5, 4}; |
| 22 | + int expectedMaxSum = 3 + 4 + -1 + 2 + 1; // max subarray is [3, 4, -1, 2, 1] |
| 23 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 24 | + } |
| 25 | + |
| 26 | + @Test |
| 27 | + void testMaxSumWithAllNegativeValues() { |
| 28 | + // Test with all negative numbers |
| 29 | + int[] input = {-2, -3, -1, -4}; |
| 30 | + int expectedMaxSum = -1; // max subarray is the least negative number |
| 31 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + void testMaxSumWithSingleElement() { |
| 36 | + // Test with a single positive element |
| 37 | + int[] input = {10}; |
| 38 | + int expectedMaxSum = 10; // max subarray is the single element |
| 39 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 40 | + |
| 41 | + // Test with a single negative element |
| 42 | + input = new int[]{-10}; |
| 43 | + expectedMaxSum = -10; // max subarray is the single element |
| 44 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + void testMaxSumWithZero() { |
| 49 | + // Test with zeros in the array |
| 50 | + int[] input = {0, -1, 2, -2, 0, 3}; |
| 51 | + int expectedMaxSum = 3; // max subarray is [2, -2, 0, 3] |
| 52 | + assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + void testMaxSumWithEmptyArray() { |
| 57 | + // Test with an empty array; should ideally throw an exception or return false |
| 58 | + int[] input = {}; |
| 59 | + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { |
| 60 | + KadaneAlgorithm.maxSum(input, 0); |
| 61 | + }); |
| 62 | + } |
| 63 | +} |
0 commit comments