TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
cut_rod.cpp
Go to the documentation of this file.
1
21#include <array>
22#include <cassert>
23#include <climits>
24#include <cstdint>
25#include <iostream>
30namespace dynamic_programming {
35namespace cut_rod {
44template <size_t T>
45int maxProfitByCuttingRod(const std::array<int, T> &price, const uint64_t &n) {
46 int *profit =
47 new int[n + 1]; // profit[i] will hold maximum profit for i inch rod
48
49 profit[0] = 0; // if length of rod is zero, then no profit
50
51 // outer loop will select size of rod, starting from 1 inch to n inch rod.
52 // inner loop will evaluate the maximum profit we can get for i inch rod by
53 // making every possible cut on it and will store it in profit[i].
54 for (size_t i = 1; i <= n; i++) {
55 int q = INT_MIN;
56 for (size_t j = 1; j <= i; j++) {
57 q = std::max(q, price[j - 1] + profit[i - j]);
58 }
59 profit[i] = q;
60 }
61 const int16_t ans = profit[n];
62 delete[] profit;
63 return ans; // returning maximum profit
64}
65} // namespace cut_rod
66} // namespace dynamic_programming
67
72static void test() {
73 // Test 1
74 const int16_t n1 = 8; // size of rod
75 std::array<int32_t, n1> price1 = {1, 2, 4, 6, 8, 45, 21, 9}; // price array
76 const int64_t max_profit1 =
77 dynamic_programming::cut_rod::maxProfitByCuttingRod(price1, n1);
78 const int64_t expected_max_profit1 = 47;
79 assert(max_profit1 == expected_max_profit1);
80 std::cout << "Maximum profit with " << n1 << " inch road is " << max_profit1
81 << std::endl;
82
83 // Test 2
84 const int16_t n2 = 30; // size of rod
85 std::array<int32_t, n2> price2 = {
86 1, 5, 8, 9, 10, 17, 17, 20, 24, 30, // price array
87 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
88 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
89
90 const int64_t max_profit2 =
91 dynamic_programming::cut_rod::maxProfitByCuttingRod(price2, n2);
92 const int32_t expected_max_profit2 = 90;
93 assert(max_profit2 == expected_max_profit2);
94 std::cout << "Maximum profit with " << n2 << " inch road is " << max_profit2
95 << std::endl;
96 // Test 3
97 const int16_t n3 = 5; // size of rod
98 std::array<int32_t, n3> price3 = {2, 9, 17, 23, 45}; // price array
99 const int64_t max_profit3 =
100 dynamic_programming::cut_rod::maxProfitByCuttingRod(price3, n3);
101 const int64_t expected_max_profit3 = 45;
102 assert(max_profit3 == expected_max_profit3);
103 std::cout << "Maximum profit with " << n3 << " inch road is " << max_profit3
104 << std::endl;
105}
106
111int main() {
112 // Testing
113 test();
114 return 0;
115}
int maxProfitByCuttingRod(const std::array< int, T > &price, const uint64_t &n)
Cuts the rod in different pieces and stores the maximum profit for each piece of the rod.
Definition cut_rod.cpp:45
static void test()
Function to test above algorithm.
Definition cut_rod.cpp:72
int main()
Main function.
Definition cut_rod.cpp:111
Implementation of cutting a rod problem.
Dynamic Programming algorithms.