Tower Breakers - The Final Battle

  • + 0 comments

    Didn't see any solution in JS, so here you go.

    // Creating a memoization cache for the nmax function
    const cache = new Map();
    
    // Defining the nmax function to calculate the maximum number of piles
    function nmax(cost) {
      if (cost < 4) return 1;
      if (cache.has(cost)) return cache.get(cost);
    
      let sum = 0;
      for (let pile = 1; pile <= Math.floor(Math.sqrt(cost)); pile++) {
        sum += nmax(cost - Math.pow(pile, 2));
      }
    
      cache.set(cost, sum);
      return sum;
    }
    
    // Defining the towerBreakers function to find the minimum cost
    function towerBreakers(n) {
      for (let cost = 0; ; cost++) {
        if (nmax(cost) >= n) return cost;
      }
    }