2383. Minimum Hours of Training to Win a Competition

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public: int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { return getRequiredEnergy(initialEnergy, energy) + getRequiredExperience(initialExperience, experience); } private: int getRequiredEnergy(int initialEnergy, const vector& energy) { return max(0, accumulate(energy.begin(), energy.end(), 0) + 1 - initialEnergy); } int getRequiredExperience(int currentExperience, const vector& experience) { int requiredExperience = 0; for (const int e : experience) { if (e >= currentExperience) { requiredExperience += e + 1 - currentExperience; currentExperience += e + 1 - currentExperience; } currentExperience += e; } return requiredExperience; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) { return getRequiredEnergy(initialEnergy, energy) + getRequiredExperience(initialExperience, experience); } private int getRequiredEnergy(int initialEnergy, int[] energy) { return Math.max(0, Arrays.stream(energy).sum() + 1 - initialEnergy); } private int getRequiredExperience(int currentExperience, int[] experience) { int requiredExperience = 0; for (final int e : experience) { if (e >= currentExperience) { requiredExperience += e + 1 - currentExperience; currentExperience += e + 1 - currentExperience; } currentExperience += e; } return requiredExperience; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: return self._getRequiredEnergy(initialEnergy, energy) + \ self._getRequiredExperience(initialExperience, experience) def _getRequiredEnergy(self, initialEnergy: int, energy: List[int]) -> int: return max(0, sum(energy) + 1 - initialEnergy) def _getRequiredExperience(self, currentExperience: int, experience: List[int]) -> int: requiredExperience = 0 for e in experience: if e >= currentExperience: requiredExperience += e + 1 - currentExperience currentExperience += e + 1 - currentExperience currentExperience += e return requiredExperience