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
21
22
23
24
class Solution {
 public:
  long long sellingWood(int m, int n, vector<vector<int>>& prices) {
    // dp[i][j] := the maximum money of cutting i x j piece of wood
    vector<vector<long>> dp(m + 1, vector<long>(n + 1));

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

    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
20
21
22
23
class Solution {
  public long sellingWood(int m, int n, int[][] prices) {
    // dp[i][j] := the maximum money of cutting i x j piece of wood
    long[][] dp = new long[m + 1][n + 1];

    for (int[] p : prices) {
      final int h = p[0];
      final int w = p[1];
      final int price = p[2];
      dp[h][w] = price;
    }

    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] := the maximum 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]