Minimum Time to Kill All Monsters — LeetCode 2403 Python Solution

HardLeetCode PremiumBit ManipulationArrayDynamic ProgrammingBitmask
Problem
#2403
Reading time
3 min

The problem

You are given an integer array power where power[i] is the power of the ith monster. You start with 0 mana points, and each day you increase your mana points by gain where gain initially is equal to 1.

Example

Input
power = [3,1,4]
Output
4
Explanation
The optimal way to beat all the monsters is to:

Python solution

Python
class Solution:
    def minimumTime(self, power: List[int]) -> int:
        @cache
        def dfs(mask: int) -> int:
            if mask == 0:
                return 0
            ans = inf
            gain = 1 + (n - mask.bit_count())
            for i, x in enumerate(power):
                if mask >> i & 1:
                    ans = min(ans, dfs(mask ^ (1 << i)) + (x + gain - 1) // gain)
            return ans

        n = len(power)
        return dfs((1 << n) - 1)

Complexity

MeasureComplexity
TimeO(2^n \times n)
SpaceO(2^n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2403. Minimum Time to Kill All Monsters is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2403. Minimum Time to Kill All Monsters?
LeetCode 2403. Minimum Time to Kill All Monsters is rated Hard on LeetCode.
What is the time complexity of LeetCode 2403. Minimum Time to Kill All Monsters?
The Python solution on this page runs in O(2^n \times n).
What is the space complexity of LeetCode 2403. Minimum Time to Kill All Monsters?
The Python solution on this page uses O(2^n) auxiliary space.
What topics does LeetCode 2403. Minimum Time to Kill All Monsters cover?
LeetCode 2403. Minimum Time to Kill All Monsters is tagged Bit Manipulation, Array, Dynamic Programming and Bitmask on LeetCode.
Is LeetCode 2403. Minimum Time to Kill All Monsters a premium problem?
Yes. LeetCode 2403. Minimum Time to Kill All Monsters is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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