Skip to content

Commit d8dc1cb

Browse files
authored
Merge pull request MukulCode#447 from vipul-027/cp
A recursive solution for Rod cutting problem
2 parents f879ec6 + 1c3bb5a commit d8dc1cb

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

cpp/Rod_cutting.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// A recursive solution for Rod cutting problem
2+
#include <bits/stdc++.h>
3+
#include <iostream>
4+
#include <math.h>
5+
using namespace std;
6+
7+
// A utility function to get the maximum of two integers
8+
int max(int a, int b) { return (a > b) ? a : b; }
9+
10+
/* Returns the best obtainable price for a rod of length n
11+
and price[] as prices of different pieces */
12+
int cutRod(int price[], int index, int n)
13+
{
14+
// base case
15+
if (index == 0) {
16+
return n * price[0];
17+
}
18+
//At any index we have 2 options either
19+
//cut the rod of this length or not cut
20+
//it
21+
int notCut = cutRod(price,index - 1,n);
22+
int cut = INT_MIN;
23+
int rod_length = index + 1;
24+
25+
if (rod_length <= n)
26+
cut = price[index]
27+
+ cutRod(price,index,n - rod_length);
28+
29+
return max(notCut, cut);
30+
}
31+
32+
/* Driver program to test above functions */
33+
int main()
34+
{
35+
int arr[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
36+
int size = sizeof(arr) / sizeof(arr[0]);
37+
cout << "Maximum Obtainable Value is "
38+
<< cutRod(arr, size - 1, size);
39+
getchar();
40+
return 0;
41+
}
42+
43+

0 commit comments

Comments
 (0)