Skip to content

Commit ace2fea

Browse files
Merge pull request #101 from sourav-naskar/main
added Rod Cutting DP problem
2 parents b03c216 + 77004e3 commit ace2fea

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
int cutRodUtil(vector<int>& price, int ind, int N, vector<vector<int>>& dp){
6+
7+
if(ind == 0){
8+
return N*price[0];
9+
}
10+
11+
if(dp[ind][N]!=-1)
12+
return dp[ind][N];
13+
14+
int notTaken = 0 + cutRodUtil(price,ind-1,N,dp);
15+
16+
int taken = INT_MIN;
17+
int rodLength = ind+1;
18+
if(rodLength <= N)
19+
taken = price[ind] + cutRodUtil(price,ind,N-rodLength,dp);
20+
21+
return dp[ind][N] = max(notTaken,taken);
22+
}
23+
24+
25+
int cutRod(vector<int>& price,int N) {
26+
27+
vector<int> cur (N+1,0);
28+
29+
for(int i=0; i<=N; i++){
30+
cur[i] = i*price[0];
31+
}
32+
33+
for(int ind=1; ind<N; ind++){
34+
for(int length =0; length<=N; length++){
35+
36+
int notTaken = 0 + cur[length];
37+
38+
int taken = INT_MIN;
39+
int rodLength = ind+1;
40+
if(rodLength <= length)
41+
taken = price[ind] + cur[length-rodLength];
42+
43+
cur[length] = max(notTaken,taken);
44+
}
45+
}
46+
47+
return cur[N];
48+
}
49+
50+
51+
52+
int main() {
53+
54+
vector<int> price = {2,5,7,8,10};
55+
56+
int n = price.size();
57+
58+
cout<<"The Maximum price generated is "<<cutRod(price,n);
59+
}
60+
61+
/*
62+
Output:
63+
64+
The Maximum price generated is 12
65+
66+
Time Complexity: O(N*N)
67+
68+
Reason: There are two nested loops.
69+
70+
Space Complexity: O(N)
71+
72+
Reason: We are using an external array of size ‘N+1’ to store only one row.
73+
74+
*/
75+
76+
// contributed by Sourav Naskar

0 commit comments

Comments
 (0)