Skip to main content
Back to problems
#2383
Easy Algorithms

Minimum hours of training to win a competition

Array Greedy
42.4% acceptance
Feb 25, 2026
386
298
You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively. You are also given two 0-indexed integer arrays energy and experience, both of length n. You will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available. Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i]. Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one. Return the minimum number of training hours required to defeat all n opponents.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_number_of_hours(initial_energy: i32, initial_experience: i32, energy: Vec<i32>, experience: Vec<i32>) -> i32 {
    let n = energy.len();
    let mut hours = 0i32;
    let total_energy: i32 = energy.iter().sum();
    if total_energy >= initial_energy {
      hours += total_energy - initial_energy + 1;
    }
    let mut exp = initial_experience;
    for i in 0..n {
      if exp <= experience[i] {
        hours += experience[i] - exp + 1;
        exp = experience[i] + 1;
      }
      exp += experience[i];
    }
    hours
  }
}