Maximum Energy Boost From Two Drinks - DP [JS]

Description 

Solution: DP

Keep track of four states:

  1. prevPrevA: The max energy ending with drink A, at the previous previous index (needed when we switch to another drink type).
  2. prevPrevB: The max energy ending with drink B, at the previous previous index (needed when we switch to another drink type).
  3. prevA: The max energy ending with drink A, at the previous index.
  4. prevB: The max energy ending with drink B, at the previous index.

For each index i, we can either

  1. Stay with the same drink type and take the energy at the previous energy ending with the same type.
  2. Switch the drink type and take the energy at the previous previous energy ending with the other type.

Update those four states as we go through each index.

Time Complexity: O(n)
Space Complexity: O(1)

function maxEnergyBoost(energyDrinkA, energyDrinkB) {
  let prevPrevA = 0, prevPrevB = 0;
  let prevA = 0, prevB = 0;
  let n = energyDrinkA.length;
  for (let i = 0; i < n; i++) {
    let currA = Math.max(energyDrinkA[i] + prevA, energyDrinkA[i] + prevPrevB);
    let currB = Math.max(energyDrinkB[i] + prevB, energyDrinkB[i] + prevPrevA);
    prevPrevA = prevA;
    prevPrevB = prevB;
    prevA = currA;
    prevB = currB;
  }
  return Math.max(prevA, prevB);
};

Comments

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

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

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

Maximum Score After Applying Operations on a Tree - DFS [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]