File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
src/Dynamic_Programming/Unbounded_Knapsack Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments