#2312

Selling Pieces of Wood

Hard
ArrayDynamic ProgrammingMemoizationDynamic ProgrammingMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n * (m + n))
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n * (m + n))Space O(m * n)

We can use dynamic programming to store the maximum profit for each piece of wood size, avoiding redundant calculations. This allows us to build up the solution efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a 2D array dp where dp[i][j] represents the maximum profit for a piece of wood of size i x j.
  2. 2Step 2: Initialize dp with direct sell prices from the prices array.
  3. 3Step 3: Iterate through all possible heights and widths, updating dp[i][j] based on possible cuts.
  4. 4Step 4: For each cut, calculate the profit from the two resulting pieces and update dp[i][j] with the maximum profit.
solution.py12 lines
1def maxProfit(m, n, prices):
2    dp = [[0] * (n + 1) for _ in range(m + 1)]
3    price_map = {(h, w): price for h, w, price in prices}
4    for (h, w), price in price_map.items():
5        dp[h][w] = max(dp[h][w], price)
6    for height in range(1, m + 1):
7        for width in range(1, n + 1):
8            for h in range(1, height):
9                dp[height][width] = max(dp[height][width], dp[h][width] + dp[height - h][width])
10            for w in range(1, width):
11                dp[height][width] = max(dp[height][width], dp[height][w] + dp[height][width - w])
12    return dp[m][n]

Complexity note: The time complexity is O(m * n * (m + n)) because we iterate through all dimensions and for each dimension, we check all possible cuts, leading to a cubic-like growth in operations.

  • 1Recursive cutting leads to overlapping subproblems.
  • 2Dynamic programming helps store results to avoid redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.