Unbounded knapsack (Tabulation)

Given list of N items where each item has some [weight, value] associated with it, put the items into a knapsack of capacity W to maximize the sum of values associated with the items. Repetition of items is allowed.

Hint

Building upon understanding of Unbounded knapsack (Memoization). Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def pick(ls, w):
  cache = [[0 for _ in range(w + 1)] for _ in range(len(ls) + 1)]

  for i in range(len(ls) - 1, -1, -1):
    for j in range(w + 1):
      take = 0

      if ls[i][1] <= j:
        take = ls[i][0] + cache[i][j - ls[i][1]]

      skip = cache[i + 1][j]
    
      cache[i][j] = max(take, skip)

  return cache[0][w]

ls = [[10, 1], [40, 3], [50, 4], [70, 5]]
W = 8

print(pick(ls, W))
// Javascript implementation
function pick(list, w) {
  const cache = [];
  
  for (let i = 0; i < list.length + 1; i++) {
    cache[i] = Array(w + 1).fill(0);
  }

  for (let i = list.length - 1; i >= 0; i--) {
    for (let j = 0; j < w + 1; j++) {
      let take = 0;

      if (list[i][1] <= j) {
        take = list[i][0] + cache[i][j - list[i][1]];
      }

      let skip = cache[i + 1][j];
    
      cache[i][j] = Math.max(take, skip);
    }
  }

  return cache[0][w];
}

const list = [[10, 1], [40, 3], [50, 4], [70, 5]];
const W = 8;

console.log(pick(list, W));