1. Recursive Exhaustive Cutting
Intuition
Recursively try every cut length j from 1 to n and add to optimal price of the remainder.
Algorithm
- Define
solve(n). - If
n <= 0, return 0. - Initialize
maxVal = -inf. - For
j = 1ton: -
maxVal = max(maxVal, price[j - 1] + solve(n - j)). - Return
maxVal.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int n, const vector<int>& price) { if (n <= 0) return 0; int maxVal = 0; for (int j = 1; j <= n; ++j) { maxVal = max(maxVal, price[j - 1] + solve(n - j, price)); } return maxVal; }public: int cutRod(vector<int>& price, int n) { return solve(n, price); }}; int main() { Solution sol; vector<int> price = {1, 5, 8, 9, 10, 17, 17, 20}; cout << "Max Value: " << sol.cutRod(price, 8) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack