From b76e41bf2ee62eba85995fe6711cff93aa9c9087 Mon Sep 17 00:00:00 2001 From: ABHISHEK-821005 <69668943+ABHISHEK-821005@users.noreply.github.com> Date: Wed, 28 Oct 2020 17:53:40 +0530 Subject: [PATCH] added a new function to improve time complexity WhatIfAllPricesAreSame(price1,n1) added this function. --- dynamic_programming/cut_rod.cpp | 49 ++++++--------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index 5aeb801f5..cbfd68298 100644 --- a/dynamic_programming/cut_rod.cpp +++ b/dynamic_programming/cut_rod.cpp @@ -41,7 +41,7 @@ namespace cut_rod { * @return maximum profit obtainable for @param n inch rod. */ template -int maxProfitByCuttingRod(const std::array &price, const int n) { +int maxProfitByCuttingRod(const std::array &price, const uint64_t &n) { int *profit = new int[n + 1]; // profit[i] will hold maximum profit for i inch rod @@ -62,48 +62,23 @@ int maxProfitByCuttingRod(const std::array &price, const int n) { return ans; // returning maximum profit } - - template bool WhatIfAllPricesAreSame(const std::array &price, const uint64_t &n){ /* - Note that if all the prices of the different lengths of rod are same the answer will be always n*price; where price=price of 1 length rod - Reason:: - cR() ---> cutRod() - - cR(4) - / / - / / - cR(3) cR(2) cR(1) cR(0) - / | / | - / | / | - cR(2) cR(1) cR(0) cR(1) cR(0) cR(0) - / | | - / | | - cR(1) cR(0) cR(0) cR(0) - / - / -CR(0) - - + Reason::--> if every length has same price , you would definitely want the rod of length 1, with n quantities. which will give us maximum profits and maximum cuts. - */ - - const int temp=price[0]; + const int16_t temp=price[0]; for (size_t i = 1; i price1 = {1, 1,1,1,1,1,1,1}; // price array - const int max_profit1 = + const int16_t n1 = 8; // size of rod + std::array price1 = {1,1,1,1,1,1,1,1}; // price array + const int64_t max_profit1 = dynamic_programming::cut_rod::maxProfitByCuttingRod(price1, n1); - const int expected_max_profit1 = 22; + const int32_t expected_max_profit1 = 22; - if(dynamic_programming::cut_rod::WhatIfAllPricesAreSame(price1,n1)){ + if (dynamic_programming::cut_rod::WhatIfAllPricesAreSame(price1,n1)) { std::cout << "Maximum profit with " << n1 << " inch road is " <<(n1)*price1[0] << std::endl; } - else{ + else { assert(max_profit1 == expected_max_profit1); std::cout << "Maximum profit with " << n1 << " inch road is " << max_profit1 << std::endl; } - - - // Test 2 const int n2 = 30; // size of rod std::array price2 = {