Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2312: Selling Pieces of Wood

In this guide, we solve Leetcode #2312 Selling Pieces of Wood in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Memoization, Array, Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

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: - 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.

Python Solution

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

The time complexity is O(m×n×(m+n)+p)O(m \times n \times (m + n) + p)O(m×n×(m+n)+p), and the space complexity is O(m×n)O(m \times n)O(m×n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy