Skip to content

Commit 503a692

Browse files
committed
Two-Hundred-Seventy Commit: Add Rod Cutting problem to Unbounded Knapsack section
1 parent 16e695a commit 503a692

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package Dynamic_Programming.Unbounded_Knapsack;
2+
3+
// Problem Statement: Rod Cutting
4+
// LeetCode Question:
5+
6+
public class Problem_2_Rod_Cutting {
7+
// Bottom-up Dynamic Programming
8+
class Solution_1 {
9+
10+
public int solveRodCutting(int[] lengths, int[] prices, int n) {
11+
// base checks
12+
if (n <= 0 || prices.length == 0 || prices.length != lengths.length)
13+
return 0;
14+
15+
int lengthCount = lengths.length;
16+
int[][] dp = new int[lengthCount][n + 1];
17+
18+
// process all rod lengths for all prices
19+
for(int i=0; i < lengthCount; i++) {
20+
for(int len=1; len <= n; len++) {
21+
int p1=0, p2=0;
22+
if(lengths[i] <= len)
23+
p1 = prices[i] + dp[i][len-lengths[i]];
24+
if( i > 0 )
25+
p2 = dp[i-1][len];
26+
dp[i][len] = Math.max(p1, p2);
27+
}
28+
}
29+
30+
// maximum price will be at the bottom-right corner.
31+
return dp[lengthCount-1][n];
32+
}
33+
}
34+
35+
}

0 commit comments

Comments
 (0)