Add code for rod cutting problem (#15891)

Co-authored-by: rajatgarg <rajatgarg@adobe.com>
This commit is contained in:
Rajat Garg 2024-02-16 22:37:18 +05:30 committed by GitHub
parent d3287d7d3e
commit 61c0c6cb92
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package com.baeldung.math.rodcutting;
import java.util.Arrays;
public class RodCuttingProblem {
static int maxRevenueG;
public static int usingRecursion(int[] prices, int n) {
if (n <= 0) {
return 0;
}
int maxRevenue = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++) {
maxRevenue = Math.max(maxRevenue, prices[i - 1] + usingRecursion(prices, n - i));
}
return maxRevenue;
}
public static int usingMemoizedRecursion(int[] prices, int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return memoizedHelper(prices, n, memo);
}
private static int memoizedHelper(int[] prices, int n, int[] memo) {
if (n <= 0) {
return 0;
}
if (memo[n] != -1) {
return memo[n];
}
int maxRevenue = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++) {
maxRevenue = Math.max(maxRevenue, prices[i - 1] + memoizedHelper(prices, n - i, memo));
}
memo[n] = maxRevenue;
return maxRevenue;
}
public static int usingDynamicProgramming(int[] prices, int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int maxRevenue = Integer.MIN_VALUE;
for (int j = 1; j <= i; j++) {
maxRevenue = Math.max(maxRevenue, prices[j - 1] + dp[i - j]);
}
dp[i] = maxRevenue;
}
return dp[n];
}
public static int usingUnboundedKnapsack(int[] prices, int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < prices.length; j++) {
if (j + 1 <= i) {
dp[i] = Math.max(dp[i], dp[i - (j + 1)] + prices[j]);
}
}
}
return dp[n];
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.math.rodcutting;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class RodCuttingProblemUnitTest {
@Test
void givenARod_whenUsingRecursion_thenFindMaxRevenue() {
int[] prices = {1, 5, 8, 9};
int rodLength = 4;
int maxRevenue = RodCuttingProblem.usingRecursion(prices, rodLength);
assertEquals(10, maxRevenue);
}
@Test
void givenARod_whenUsingMemoizedRecursion_thenFindMaxRevenue() {
int[] prices = {1, 5, 8, 9};
int rodLength = 4;
int maxRevenue = RodCuttingProblem.usingMemoizedRecursion(prices, rodLength);
assertEquals(10, maxRevenue);
}
@Test
void givenARod_whenUsingDynamicProgramming_thenFindMaxRevenue() {
int[] prices = {1, 5, 8, 9};
int rodLength = 4;
int maxRevenue = RodCuttingProblem.usingDynamicProgramming(prices, rodLength);
assertEquals(10, maxRevenue);
}
@Test
void givenARod_whenUsingGreedy_thenFindMaxRevenue() {
int[] prices = {1, 5, 8, 9};
int rodLength = 4;
int maxRevenue = RodCuttingProblem.usingUnboundedKnapsack(prices, rodLength);
assertEquals(10, maxRevenue);
}
}