Selling Pieces of Wood - DP w/ Memoization [JS]

Description 

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

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]