Skip to content

Commit fa49a23

Browse files
Add selling pieces of wood problem
1 parent a74ca23 commit fa49a23

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// https://leetcode.com/problems/selling-pieces-of-wood/
2+
3+
/**
4+
* LOGIC: Problem is a basic dp problem - just understand question properly
5+
*/
6+
class Solution {
7+
public:
8+
long long helper(int rows, int cols, vector<vector<int>>& prices,
9+
vector<vector<long long>>& dp) {
10+
if(rows==0 || cols==0) return 0;
11+
if(dp[rows][cols]!=-1) return dp[rows][cols];
12+
13+
long long maxMoney = prices[rows][cols];
14+
15+
// cut from row
16+
for(int i=1;i<rows;i++) {
17+
long long currMaxPrice1 = helper(i, cols, prices, dp);
18+
long long currMaxPrice2 = helper(rows-i, cols, prices, dp);
19+
maxMoney = max(currMaxPrice1 + currMaxPrice2, maxMoney);
20+
}
21+
22+
// cut from col
23+
for(int i=1;i<cols;i++) {
24+
long long currMaxPrice1 = helper(rows, i, prices, dp);
25+
long long currMaxPrice2 = helper(rows, cols-i, prices, dp);
26+
maxMoney = max(currMaxPrice1 + currMaxPrice2, maxMoney);
27+
}
28+
29+
return dp[rows][cols] = maxMoney;
30+
}
31+
32+
long long sellingWood(int m, int n, vector<vector<int>>& prices) {
33+
vector<vector<int>> myArrPrice(m+1, vector<int>(n+1, 0));
34+
35+
for(int i=0;i<prices.size();i++)
36+
myArrPrice[prices[i][0]][prices[i][1]]=prices[i][2];
37+
38+
vector<vector<long long>> dp(m+1, vector<long long>(n+1, -1));
39+
40+
return helper(m, n, myArrPrice, dp);
41+
}
42+
};

0 commit comments

Comments
 (0)