Selling Pieces of Wood - DP w/ Memoization [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: DP w/ Memoization
First, change prices so that we can look up the price in O(1)
time.
Memoize the result of each (width, height)
, take the maximum earnings from a piece of wood with those measurements.
Given the width and height of a piece of wood, we can make horizontal or vetical cuts.
Try each of the different sized horizontal and vertical cuts.
Take the maximum price out of all the different ways of cutting.
Time Complexity: O(m * n * (m + n))
810ms
Space Complexity: O(mn)
63.6MB
var sellingWood = function(m, n, prices) {
let price = Array(n + 1).fill(0).map(() => Array(m + 1).fill(0));
for (let [height, width, woodPrice] of prices) {
price[width][height] = woodPrice;
}
let memo = Array(n + 1).fill(0).map(() => Array(m + 1).fill(-1));
return dfs(n, m);
function dfs(width, height) {
if (width === 0 || height === 0) return 0;
if (memo[width][height] !== -1) return memo[width][height];
let ans = price[width][height];
for (let h = 1; h <= Math.floor(height / 2); h++) {
ans = Math.max(ans, dfs(width, h) + dfs(width, height - h));
}
for (let w = 1; w <= Math.floor(width / 2); w++) {
ans = Math.max(ans, dfs(w, height) + dfs(width - w, height));
}
return memo[width][height] = ans;
}
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment