From 0d3bb4293c9dd60bdcb00d856419fba3793f3155 Mon Sep 17 00:00:00 2001 From: Reshma <101700293+reshmascode@users.noreply.github.com> Date: Sat, 22 Oct 2022 10:52:03 +0530 Subject: [PATCH] added solution for Rod Cutting Problem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We are given an array price[], where the rod of length i has a value price[i-1]. The idea is simple – one by one, partition the given rod of length n into two parts: i and n-i. Recur for the rod of length n-i but don’t divide the rod of length i any further. Finally, take the maximum of all values. This yields the following recursive relation: rodcut(n) = max { price[i – 1] + rodCut(n – i) } where 1 <= i <= n --- Rod-Cutting-Problem.cpp | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Rod-Cutting-Problem.cpp diff --git a/Rod-Cutting-Problem.cpp b/Rod-Cutting-Problem.cpp new file mode 100644 index 0000000..15b7b04 --- /dev/null +++ b/Rod-Cutting-Problem.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +// Function to find the best way to cut a rod of length `n` +// where the rod of length `i` has a cost `price[i-1]` +int rodCut(int price[], int n) +{ + // base case + if (n == 0) { + return 0; + } + + int maxValue = INT_MIN; + + // one by one, partition the given rod of length `n` into two parts + // of length (1, n-1), (2, n-2), (3, n-3), … ,(n-1, 1), (n, 0) + // and take maximum + for (int i = 1; i <= n; i++) + { + // rod of length `i` has a cost `price[i-1]` + int cost = price[i - 1] + rodCut(price, n - i); + + if (cost > maxValue) { + maxValue = cost; + } + } + + return maxValue; +} + +int main() +{ + int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; + + // rod length + int n = 4; + + cout << "Profit is " << rodCut(price, n); + + return 0; +}