You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.
Return the maximum money you can earn after cutting an m x n piece of wood.
Note that you can cut the piece of wood as many times as you want.
Example 1:
Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]] Output: 19 Explanation: The diagram above shows a possible scenario. It consists of: - 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14. - 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 14 + 3 + 2 = 19 money earned. It can be shown that 19 is the maximum amount of money that can be earned.
Example 2:
Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]] Output: 32 Explanation: The diagram above shows a possible scenario. It consists of: - 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 30 + 2 = 32 money earned. It can be shown that 32 is the maximum amount of money that can be earned. Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.
Constraints:
1 <= m, n <= 2001 <= prices.length <= 2 * 104prices[i].length == 31 <= hi <= m1 <= wi <= n1 <= pricei <= 106(hi, wi) are pairwise distinct.Problem Overview: You have an m x n wooden board and a list of prices for smaller rectangles. You can cut the board horizontally or vertically any number of times. The goal is to maximize the total selling price of the pieces you produce.
Approach 1: Recursive Backtracking with Memoization (Time: O(m*n*(m+n)), Space: O(m*n))
This approach treats every rectangle (h, w) as a subproblem. If a direct price exists for that size, you can sell it immediately. Otherwise, try every possible horizontal cut and vertical cut, recursively compute the best value for each resulting piece, and combine the profits. Memoization stores results for previously computed dimensions so the same rectangle size is never recomputed. This converts an exponential brute-force search into a manageable dynamic programming problem. The recursion naturally models the decision tree of splitting wood, while the cache ensures each (h, w) state is evaluated once.
Approach 2: Bottom-Up Dynamic Programming (Time: O(m*n*(m+n)), Space: O(m*n))
Create a 2D DP table where dp[h][w] stores the maximum profit for a rectangle of height h and width w. Initialize the table using the provided price list. Then iterate through all board sizes from smaller rectangles to larger ones. For each state, try all horizontal splits (1..h-1) and vertical splits (1..w-1), updating the value with dp[i][w] + dp[h-i][w] or dp[h][j] + dp[h][w-j]. This works because any optimal solution for a large rectangle must be composed of optimal solutions for smaller rectangles. The approach is a classic 2D partition DP pattern commonly used in cutting and segmentation problems.
Both methods rely heavily on dynamic programming and overlapping subproblems. The recursive variant uses memoization to cache computed states, while the bottom-up version iteratively fills the table. The input price list is typically stored in a lookup structure derived from the array input.
Recommended for interviews: The bottom-up dynamic programming approach. Interviewers expect candidates to recognize this as a 2D DP partition problem similar to rod cutting but extended to rectangles. Explaining the recursive memoized solution first shows you understand the recurrence, while converting it into iterative DP demonstrates stronger optimization and implementation skills.
This approach uses dynamic programming to find the maximum profit from cutting the wood into smaller pieces.
DP Table Setup: We'll create a 2D DP array where dp[i][j] represents the maximum profit from a piece of wood with dimensions i x j.
Recurrence Relations: For each piece of wood with dimensions i x j, try all possible horizontal and vertical cuts and maximize the resultant profit. Additionally, if there's a direct price available for i x j, consider that as well.
Iterate over all dimensions and calculate the maximum profit possible for each sub-dimension.
The function max_earnings calculates the maximum money by using a dynamic programming approach. Initially, we create a dictionary price_dict to store prices for each dimension pair.
We then initiate a 2D list dp with dimensions (m+1) x (n+1). As we iterate over each dimension, we update the dp table by considering all horizontal and vertical splits and lookup for direct prices.
Finally, return dp[m][n] as it contains the result for the original piece size.
Time Complexity: O(m * n * (m + n)) due to nested loops iterating over dimensions and possible splits.
Space Complexity: O(m * n) for storing results in the dp table.
This approach employs recursive backtracking, utilizing memoization to eliminate redundant calculations and improve efficiency.
We'll use a helper function for recursion. For given dimensions m x n, we will attempt all cuts, calling the function recursively, and calculate potential profits from any direct price or cut scenarios.
To prevent recalculating results for the same dimensions, a memoization dictionary stores previously computed results.
This Python implementation uses a recursive function dfs for performing all splits of wood and calculating prospective profits at each step through depth-first traversal.
A memoization dictionary optimizes performance by storing known results.
Time Complexity: O(m * n) due to memoization limiting recursive calls purely to unique dimensions.
Space Complexity: O(m * n) based on stack frames occupied during recursion leading to saved subsolution results.
First, we define a 2D array d, where d[i][j] represents the price of a wood block with height i and width j.
Then, we design a function dfs(h, w) to denote the maximum amount of money obtained by cutting a wood block with height h and width w. The answer will be dfs(m, n).
The process of function dfs(h, w) is as follows:
(h, w) has been calculated before, return the answer directly.d[h][w], then enumerate the cutting positions, calculate the maximum amount of money obtained by cutting the wood block into two pieces, and take the maximum value.The time complexity is O(m times n times (m + n) + p), and the space complexity is O(m times n). Here, p represents the length of the price array, while m and n represent the height and width of the wood blocks, respectively.
Python
Java
C++
Go
TypeScript
We can transform the memoization search in Solution 1 into dynamic programming.
Similar to Solution 1, we define a 2D array d, where d[i][j] represents the price of a wood block with height i and width j. Initially, we iterate through the price array prices and store the price p of each wood block (h, w, p) in d[h][w], while the rest of the prices are set to 0.
Then, we define another 2D array f, where f[i][j] represents the maximum amount of money obtained by cutting a wood block with height i and width j. The answer will be f[m][n].
Considering how f[i][j] transitions, initially f[i][j] = d[i][j]. We enumerate the cutting positions, calculate the maximum amount of money obtained by cutting the wood block into two pieces, and take the maximum value.
The time complexity is O(m times n times (m + n) + p), and the space complexity is O(m times n). Here, p represents the length of the price array, while m and n represent the height and width of the wood blocks, respectively.
Similar problems:
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(m * n * (m + n)) due to nested loops iterating over dimensions and possible splits. Space Complexity: O(m * n) for storing results in the dp table. |
| Recursive Backtracking with Memoization | Time Complexity: O(m * n) due to memoization limiting recursive calls purely to unique dimensions. Space Complexity: O(m * n) based on stack frames occupied during recursion leading to saved subsolution results. |
| Memoization Search | — |
| Dynamic Programming | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Recursive Backtracking with Memoization | O(m*n*(m+n)) | O(m*n) | When deriving the recurrence relation first or explaining the problem during interviews |
| Bottom-Up Dynamic Programming | O(m*n*(m+n)) | O(m*n) | Best practical implementation; avoids recursion overhead and clearly builds optimal solutions |
Complete Weekly Contest 298 | Leetcode 2312 Selling Pieces of Wood| Live coding | Easy Peasy DP 🔥🔥 • Coding Decoded • 2,016 views views
Watch 7 more video solutions →Practice Selling Pieces of Wood with our built-in code editor and test cases.
Practice on FleetCode