Skip to content

2312. Selling Pieces of Wood 👍

  • Time: $O(\max(m^2n, mn^2))$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  long long sellingWood(int m, int n, vector<vector<int>>& prices) {
    // dp[i][j] := max money of cutting i x j piece of wood
    vector<vector<long long>> dp(m + 1, vector<long long>(n + 1));

    for (const vector<int>& p : prices)
      dp[p[0]][p[1]] = p[2];

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j) {
        for (int h = 1; h <= i / 2; ++h)
          dp[i][j] = max(dp[i][j], dp[h][j] + dp[i - h][j]);
        for (int w = 1; w <= j / 2; ++w)
          dp[i][j] = max(dp[i][j], dp[i][w] + dp[i][j - w]);
      }

    return dp[m][n];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public long sellingWood(int m, int n, int[][] prices) {
    // dp[i][j] := max money of cutting i x j piece of wood
    long[][] dp = new long[m + 1][n + 1];

    for (int[] p : prices)
      dp[p[0]][p[1]] = p[2];

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j) {
        for (int h = 1; h <= i / 2; ++h)
          dp[i][j] = Math.max(dp[i][j], dp[h][j] + dp[i - h][j]);
        for (int w = 1; w <= j / 2; ++w)
          dp[i][j] = Math.max(dp[i][j], dp[i][w] + dp[i][j - w]);
      }

    return dp[m][n];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
    # dp[i][j] := max money of cutting i x j piece of wood
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for h, w, price in prices:
      dp[h][w] = price

    for i in range(1, m + 1):
      for j in range(1, n + 1):
        for h in range(1, i // 2 + 1):
          dp[i][j] = max(dp[i][j], dp[h][j] + dp[i - h][j])
        for w in range(1, j // 2 + 1):
          dp[i][j] = max(dp[i][j], dp[i][w] + dp[i][j - w])

    return dp[m][n]