Maximum Value of K Coins From Piles - Knapsack - DP [JS]

Description

Solution: Knapsack - DP

dp[i][k] = maximum sum of taking k coins from the first i piles.

For each pile, try taking from 0 to k of the top coins from it.
Memoize the results in a 2D matrix to save time.

Time Complexity:O(nk^2)377ms
Space Complexity: O(nk) 53.6MB

var maxValueOfCoins = function(piles, k) {
  let n = piles.length, dp = Array(n).fill(0).map(() => Array(k + 1).fill(-1));
  return dfs(0, k);

  function dfs(idx, k) {
    if (idx === n || k === 0) return 0;
    if (dp[idx][k] !== -1) return dp[idx][k];
    let sum = 0;
    for (let j = 0; j <= Math.min(k, piles[idx].length); j++) {
      dp[idx][k] = Math.max(dp[idx][k], dfs(idx + 1, k - j) + sum);
      if (j < piles[idx].length) sum += piles[idx][j];
    }
    return dp[idx][k];
  }
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]