Selling Pieces of Wood — LeetCode 2312 Python Solution

HardMemoizationArrayDynamic Programming
Problem
#2312
Reading time
3 min

The problem

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.

Example

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:

Python solution

Python
class Solution:
    def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
        @cache
        def dfs(h: int, w: int) -> int:
            ans = d[h].get(w, 0)
            for i in range(1, h // 2 + 1):
                ans = max(ans, dfs(i, w) + dfs(h - i, w))
            for i in range(1, w // 2 + 1):
                ans = max(ans, dfs(h, i) + dfs(h, w - i))
            return ans

        d = defaultdict(dict)
        for h, w, p in prices:
            d[h][w] = p
        return dfs(m, n)

Complexity

MeasureComplexity
TimeO(m \times n \times (m + n) + p)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2312. Selling Pieces of Wood is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2312. Selling Pieces of Wood?
LeetCode 2312. Selling Pieces of Wood is rated Hard on LeetCode.
What is the time complexity of LeetCode 2312. Selling Pieces of Wood?
The Python solution on this page runs in O(m \times n \times (m + n) + p).
What is the space complexity of LeetCode 2312. Selling Pieces of Wood?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 2312. Selling Pieces of Wood cover?
LeetCode 2312. Selling Pieces of Wood is tagged Memoization, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview