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.
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.length
3 <= n <= 105
1 <= energyDrinkA[i], energyDrinkB[i] <= 105
Solutions
Solution 1: Dynamic Programming
Thinking
Each hour we drink A or B, and switching costs a clean hour. \(n\le 10^5\) forbids enumerating switch points. The optimum at hour \(i\) depends only on which drink was last chosen.
\(f[i][0]\) / \(f[i][1]\) are the best scores ending on A / B: continue the same drink and add today's value, or come from the other drink as a clean gap without adding. The answer is the larger last-row entry.
We define \(f[i][0]\) to represent the maximum boost energy obtained by choosing energy drink A at the \(i\)-th hour, and \(f[i][1]\) to represent the maximum boost energy obtained by choosing energy drink B at the \(i\)-th hour. Initially, \(f[0][0] = \textit{energyDrinkA}[0]\), \(f[0][1] = \textit{energyDrinkB}[0]\). The answer is \(\max(f[n - 1][0], f[n - 1][1])\).
For \(i > 0\), we have the following state transition equations:
Solution 1 reads only \(f[i-1]\), so the table collapses to two variables. Rolling \(f,g\) store the best scores for A and B; space becomes \(O(1)\) at the same time.
We notice that the state \(f[i]\) is only related to \(f[i - 1]\) and not to \(f[i - 2]\). Therefore, we can use only two variables \(f\) and \(g\) to maintain the state, thus optimizing the space complexity to \(O(1)\).
The time complexity is \(O(n)\), where \(n\) is the length of the array. The space complexity is \(O(1)\).