#2383

Minimum Hours of Training to Win a Competition

Easy
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal approach involves calculating the minimum training required for both energy and experience separately, and summing them up. This avoids unnecessary training and focuses on the minimum needed to defeat each opponent.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize total training hours to 0.
  2. 2Step 2: For each opponent, check if current energy and experience are sufficient.
  3. 3Step 3: If not, calculate the difference needed for both energy and experience.
  4. 4Step 4: Update the total training hours and the current energy and experience after defeating the opponent.
solution.py12 lines
1def minTrainingHours(initialEnergy, initialExperience, energy, experience):
2    total_hours = 0
3    for i in range(len(energy)):
4        if initialEnergy <= energy[i]:
5            total_hours += energy[i] - initialEnergy + 1
6            initialEnergy = energy[i] + 1
7        if initialExperience <= experience[i]:
8            total_hours += experience[i] - initialExperience + 1
9            initialExperience = experience[i] + 1
10        initialEnergy -= energy[i]
11        initialExperience += experience[i]
12    return total_hours

Complexity note: The complexity is O(n) because we only loop through the opponents once, calculating the necessary training in constant time.

  • 1Training can be done in a focused manner, addressing only the deficits in energy and experience.
  • 2The order of opponents matters; always address the current opponent's requirements before moving on.

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