#3259

Maximum Energy Boost From Two Drinks

Medium
ArrayDynamic ProgrammingDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to keep track of the maximum energy boost possible at each hour, considering whether the last drink was from A or B. This avoids redundant calculations and significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two arrays dpA and dpB to store maximum energy boosts when the last drink is from A or B respectively.
  2. 2Step 2: Set dpA[0] and dpB[0] to the first elements of energyDrinkA and energyDrinkB.
  3. 3Step 3: Iterate through the hours, updating dpA and dpB based on the previous values, considering the cleanse hour when switching drinks.
solution.py11 lines
1def maxEnergyBoost(energyDrinkA, energyDrinkB):
2    n = len(energyDrinkA)
3    dpA = [0] * n
4    dpB = [0] * n
5    dpA[0] = energyDrinkA[0]
6    dpB[0] = energyDrinkB[0]
7    for i in range(1, n):
8        dpA[i] = max(dpA[i-1] + energyDrinkA[i], dpB[i-1])
9        dpB[i] = max(dpB[i-1] + energyDrinkB[i], dpA[i-1])
10    return max(dpA[n-1], dpB[n-1])
11

Complexity note: The time complexity is linear because we only make a single pass through the arrays, updating our dp arrays in constant time for each hour. The space complexity is also linear due to the storage of the dp arrays.

  • 1Switching drinks incurs a penalty of one hour without energy.
  • 2Dynamic programming allows us to efficiently track maximum energy boosts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.