Print maximum number of A’s using given four keys (Tabulation)

Give a special keyboard with the following four keys Key 1: Prints 'A' on screen, Key 2: Select screen, Key 3: Copy selection, Key 4: Paste selection on screen after what has already been printed. Given a number N times (with the above four keys), write a program to produce maximum numbers of A's.

Hint

Building upon understanding of Print maximum number of A’s using given four keys (Memoization). Pay attention to the cache. 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 count(n):
  cache = [0] * (n)

  for i in range(1, 7):
    cache[i - 1] = i
  
  for i in range(7, n + 1):
    for j in range(i - 3, 0, -1):
      cache[i - 1] = max(cache[i - 1], (i - j - 1) * cache[j - 1])
  
  return cache[n - 1]

n = 9

print(count(n))
// Javascript implementation
function count(n) {
  const cache = Array(n).fill(0);

  for (let i = 1; i < 7; i++) {
    cache[i - 1] = i;
  }

  for (let i = 7; i < n + 1; i++) {
    for (let j = i - 3; j > 0; j--) {
      cache[i - 1] = Math.max(cache[i - 1], (i - j - 1) * cache[j - 1]);
    }
  }
  
  return cache[n - 1];
}

const n = 7;

console.log(count(n));