Leetcode 2383. Minimum Hours of Training to Win a Competition
Leetcode Problem 2383: Minimum Hours of Training to Win a Competition
You are given two integers initialEnergy
and initialExperience
. You are also given two integer arrays energy
and experience
, both of length n
.
You are competing in n
training sessions where the i-th
session has:
energy[i]
experience[i]
amount of experience to defeat the opponent in the training session.You can defeat the opponent in the i-th
session if you both:
initialEnergy
must be greater than energy[i]
.initialExperience
must be greater than experience[i]
.Each time you defeat an opponent, your experience increases by experience[i]
. Also, you can choose to train to increase your experience by 1 unit in one hour, and you can increase your energy by 1 unit in one hour as well.
Return the minimum number of hours of training needed to defeat all the opponents in the n
training sessions.
n
?
n
can be up to 1000.energy
and experience
arrays be negative or zero?
energy
and experience
will be positive integers.initialEnergy
or initialExperience
be zero or negative?
initialEnergy
and initialExperience
will be positive integers.initialEnergy
and initialExperience
?
10^5
).The strategy to solve this problem involves:
#include <vector>
#include <algorithm>
class Solution {
public:
int minNumberOfHours(int initialEnergy, int initialExperience, std::vector<int>& energy, std::vector<int>& experience) {
int n = energy.size();
int requiredEnergy = 0, totalHours = 0;
// Calculate the total energy required to defeat all opponents.
for (int i = 0; i < n; ++i) {
requiredEnergy += energy[i];
}
// If the initial energy is less than required, calculate the additional hours needed.
if (initialEnergy <= requiredEnergy) {
totalHours += requiredEnergy - initialEnergy + 1;
}
// Process each training session.
for (int i = 0; i < n; ++i) {
if (initialExperience <= experience[i]) {
totalHours += experience[i] - initialExperience + 1;
initialExperience = experience[i] + 1;
}
// Simulate defeating the opponent and increasing experience.
initialExperience += experience[i];
}
return totalHours;
}
};
energy
and experience
arrays once.This solution ensures that you have enough energy and experience to win all training sessions while computing the minimal hours of training required efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?