Maximum Energy Boost From Two Drinks Problem
Description
LeetCode Problem 3259.
You are given two integer arrays energyDrinkA and energyDrinkB of the same length n by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.
You want to maximize your total energy boost by drinking one energy drink per hour. However, if you want to switch from consuming one energy drink to the other, you need to wait for one hour to cleanse your system (meaning you won't get any energy boost in that hour).
Return the maximum total energy boost you can gain in the next n hours.
Note that you can start consuming either of the two energy drinks.
Example 1:
Input: energyDrinkA = [1,3,1], energyDrinkB = [3,1,1]
Output: 5
Explanation:
To gain an energy boost of 5, drink only the energy drink A (or only B).
Example 2:
Input: energyDrinkA = [4,1,1], energyDrinkB = [1,1,3]
Output: 7
Explanation:
To gain an energy boost of 7:
- Drink the energy drink A for the first hour.
- Switch to the energy drink B and we lose the energy boost of the second hour.
- Gain the energy boost of the drink B in the third hour.
Constraints:
n == energyDrinkA.length == energyDrinkB.length3 <= n <= 10^51 <= energyDrinkA[i], energyDrinkB[i] <= 10^5
Solution
Approach: Dynamic Programming
Switching drinks costs one idle hour. Let f[i][0] be the best total after hour i when drink A is the one in use, where hour i is either an A boost or the idle hour spent switching to A. Define f[i][1] the same way for B. Then:
f[i][0] = max(f[i-1][0] + A[i], f[i-1][1]) and f[i][1] = max(f[i-1][1] + B[i], f[i-1][0]).
The first option keeps drinking A; the second spends hour i idle after drinking B in hour i - 1. Start with f[0] = [A[0], B[0]]; the answer is the larger value in the last row. Only the previous row is needed.
Complexity: O(n) time and O(n) space as written (O(1) with two rolling variables).
class Solution:
def maxEnergyBoost(self, energyDrinkA: List[int], energyDrinkB: List[int]) -> int:
n = len(energyDrinkA)
f = [[0] * 2 for _ in range(n)]
f[0][0] = energyDrinkA[0]
f[0][1] = energyDrinkB[0]
for i in range(1, n):
f[i][0] = max(f[i - 1][0] + energyDrinkA[i], f[i - 1][1])
f[i][1] = max(f[i - 1][1] + energyDrinkB[i], f[i - 1][0])
return max(f[n - 1])