Minimum Hours of Training to Win a Competition — LeetCode 2383 Python Solution

EasyGreedyArray
Problem
#2383
Pattern
Greedy
Reading time
4 min

The problem

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.

Example

Input
initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]
Output
8
Explanation
You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.

Python solution

Python
class Solution:
    def minNumberOfHours(
        self, x: int, y: int, energy: List[int], experience: List[int]
    ) -> int:
        ans = 0
        for dx, dy in zip(energy, experience):
            if x <= dx:
                ans += dx + 1 - x
                x = dx + 1
            if y <= dy:
                ans += dy + 1 - y
                y = dy + 1
            x -= dx
            y += dy
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the number of opponents
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2383. Minimum Hours of Training to Win a Competition is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2383. Minimum Hours of Training to Win a Competition?
LeetCode 2383. Minimum Hours of Training to Win a Competition is rated Easy on LeetCode.
What is the time complexity of LeetCode 2383. Minimum Hours of Training to Win a Competition?
The Python solution on this page runs in O(n), where n is the number of opponents.
What is the space complexity of LeetCode 2383. Minimum Hours of Training to Win a Competition?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2383. Minimum Hours of Training to Win a Competition cover?
LeetCode 2383. Minimum Hours of Training to Win a Competition is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview