LeetCode 2383: Minimum Hours of Training to Win a Competition

ArrayGreedy

Problem Description

Explanation:

To solve this problem, we need to find the minimum number of training hours required to defeat all opponents. We can approach this by simulating the competition process. We iterate through each opponent and calculate the required energy and experience to defeat them. Then, we update our current energy and experience based on the results. We keep track of the total training hours needed.

  • Sort the opponents based on their energy and experience requirements.
  • Initialize current energy and experience to initialEnergy and initialExperience.
  • Iterate through each opponent:
    • If our current energy and experience are sufficient to defeat the opponent, update the current energy and experience accordingly.
    • If not, calculate the additional energy or experience required and update accordingly.
  • Return the total training hours needed.

Time Complexity: O(n log n) where n is the number of opponents due to sorting the opponents array.

Space Complexity: O(1) as we are using constant extra space.

:

Solutions

class Solution {
    public int minHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) {
        int n = energy.length;
        int hours = 0;
        
        int[][] opponents = new int[n][2];
        for (int i = 0; i < n; i++) {
            opponents[i][0] = energy[i];
            opponents[i][1] = experience[i];
        }
        
        Arrays.sort(opponents, (a, b) -> a[0] - b[0]);
        
        for (int[] opponent : opponents) {
            int energyNeeded = Math.max(0, opponent[0] - initialEnergy);
            int experienceNeeded = Math.max(0, opponent[1] - initialExperience);
            
            hours += energyNeeded + experienceNeeded;
            initialEnergy += energyNeeded;
            initialExperience += experienceNeeded;
        }
        
        return hours;
    }
}

Loading editor...