[LeetCode] Selling Pieces of Wood

2312. Selling Pieces of Wood

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.

To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.

Return the maximum money you can earn after cutting an m x n piece of wood.

Note that you can cut the piece of wood as many times as you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
long long dp[202][202];
long long c[202][202];

long long helper(int n, int m) {
if(dp[n][m] != -1) return dp[n][m];
long long& res = dp[n][m] = c[n][m];
for(int i = 1; i < n; i++) { // divide with row
res = max(res, helper(i,m) + helper(n-i, m));
}
for(int i = 1; i < m; i++) { // divide with col
res = max(res, helper(n,i) + helper(n,m-i));
}
return res;
}
public:
long long sellingWood(int n, int m, vector<vector<int>>& prices) {
memset(dp, -1, sizeof dp);
memset(c, 0, sizeof c);
for(auto& p : prices) {
long long y = p[0], x = p[1], w = p[2];
c[y][x] = max(c[y][x], w);
}

return helper(n,m);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/19/PS/LeetCode/selling-pieces-of-wood/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.