# Program to find maximum profit by cutting the rod of different length in C++

Suppose we have a rod is given of length n. We also have a list, that contains different size and price for each size. We have to find the maximum price by cutting the rod and selling them in the market. To get the best price by making a cut at different positions and comparing the prices after cutting the rod.

So, if the input is like prices = [1, 5, 8, 9, 10, 17, 17, 20], n = 8, then the output will be 22, as by cutting the rod in length 2 and 6. The profit is 5 + 17 = 22.

To solve this, we will follow these steps −

• Define an array profit of size: n+1.

• profit[0] := 0

• for initialize i := 1, when i <= n, update (increase i by 1), do −

• maxProfit := negative infinity

• for initialize j := 0, when j < i, update (increase j by 1), do −

• maxProfit := maximum of maxProfit and price[j] + profit[i − j − 1]

• profit[i] := maxProfit

• return maxProfit

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int max(int a, int b) {
return (a > b)? a : b;
}
int rodCutting(int price[], int n) {
int profit[n+1];
profit[0] = 0;
int maxProfit;
for (int i = 1; i<=n; i++) {
maxProfit = INT_MIN;
for (int j = 0; j < i; j++)
maxProfit = max(maxProfit, price[j] + profit[i-j-1]);
profit[i] = maxProfit;
}
return maxProfit;
}
int main() {
int priceList[] = {1, 5, 8, 9, 10, 17, 17, 20};
int rodLength = 8;
cout << rodCutting(priceList, rodLength);
}

## Input

{1, 5, 8, 9, 10, 17, 17, 20}, 8

## Output

22

Advertisements