diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index 9513e487e..c365be4fc 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 @@ -57,7 +57,7 @@ int maxProfitByCuttingRod(const std::array &price, const int n) { } profit[i] = q; } - int ans = profit[n]; + const int16_t ans = profit[n]; delete[] profit; return ans; // returning maximum profit } @@ -70,27 +70,37 @@ int maxProfitByCuttingRod(const std::array &price, const int n) { */ static void test() { // Test 1 - const int n1 = 8; // size of rod - std::array price1 = {1, 5, 8, 9, 10, 17, 17, 20}; // price array - const int max_profit1 = + const int16_t n1 = 8; // size of rod + std::array price1 = {1,2,4,6,8,45,21,9}; // price array + const int64_t max_profit1 = dynamic_programming::cut_rod::maxProfitByCuttingRod(price1, n1); - const int expected_max_profit1 = 22; + const int64_t expected_max_profit1 = 47; 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 = { + const int16_t n2 = 30; // size of rod + std::array price2 = { 1, 5, 8, 9, 10, 17, 17, 20, 24, 30, // price array 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; - const int max_profit2 = + + const int64_t max_profit2= dynamic_programming::cut_rod::maxProfitByCuttingRod(price2, n2); - const int expected_max_profit2 = 90; + const int32_t expected_max_profit2 = 90; assert(max_profit2 == expected_max_profit2); std::cout << "Maximum profit with " << n2 << " inch road is " << max_profit2 << std::endl; + // Test 3 + const int16_t n3 = 5; // size of rod + std::array price3 = {2,9,17,23,45}; // price array + const int64_t max_profit3 = + dynamic_programming::cut_rod::maxProfitByCuttingRod(price3, n3); + const int64_t expected_max_profit3 = 45; + assert(max_profit3 == expected_max_profit3); + std::cout << "Maximum profit with " << n3 << " inch road is " << max_profit3 + << std::endl; } /**