Skip to content

3259. Maximum Energy Boost From Two Drinks 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  long long maxEnergyBoost(vector<int>& energyDrinkA,
                           vector<int>& energyDrinkB) {
    long dpA = 0;  // the maximum energy boost if the last drink is A
    long dpB = 0;  // the maximum energy boost if the last drink is B

    for (int i = 0; i < energyDrinkA.size(); ++i) {
      const long newDpA = max(dpB, dpA + energyDrinkA[i]);
      const long newDpB = max(dpA, dpB + energyDrinkB[i]);
      dpA = newDpA;
      dpB = newDpB;
    }

    return max(dpA, dpB);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public long maxEnergyBoost(int[] energyDrinkA, int[] energyDrinkB) {
    long dpA = 0; // the maximum energy boost if the last drink is A
    long dpB = 0; // the maximum energy boost if the last drink is B

    for (int i = 0; i < energyDrinkA.length; ++i) {
      final long newDpA = Math.max(dpB, dpA + energyDrinkA[i]);
      final long newDpB = Math.max(dpA, dpB + energyDrinkB[i]);
      dpA = newDpA;
      dpB = newDpB;
    }

    return Math.max(dpA, dpB);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maxEnergyBoost(
      self,
      energyDrinkA: list[int],
      energyDrinkB: list[int]
  ) -> int:
    dpA = 0  # the maximum energy boost if the last drink is A
    dpB = 0  # the maximum energy boost if the last drink is B

    for a, b in zip(energyDrinkA, energyDrinkB):
      dpA, dpB = max(dpB, dpA + a), max(dpA, dpB + b)

    return max(dpA, dpB)