Minimum Time to Kill All Monsters - 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.

Each day, after gaining gain mana, you can defeat a monster if your mana points are greater than or equal to the power of that monster. When you defeat a monster:

  • Your mana points will be reset to 0
  • The value of gain increases by 1

Return the minimum number of days needed to defeat all the monsters.

Input & Output

Example 1 — Basic Case
$ Input: power = [3,1,4]
Output: 7
💡 Note: Optimal order [4,3,1]: Day 1-4 build mana to defeat monster with power 4 (gain becomes 2), Day 5-6 build mana to defeat monster with power 3 (gain becomes 3), Day 7 defeat monster with power 1. Total: 7 days.
Example 2 — Small Array
$ Input: power = [1,1,4]
Output: 3
💡 Note: Optimal order [1,1,4]: Day 1 defeat first monster (gain=2), Day 2 defeat second monster (gain=3), Day 3 defeat monster with power 4 (have 3 mana, need 4, so gain 3 more = 6 total). Total: 3 days.
Example 3 — Single Monster
$ Input: power = [2]
Output: 2
💡 Note: Only one monster with power 2. Need 2 days to build enough mana (gain=1 each day). Total: 2 days.

Constraints

  • 1 ≤ power.length ≤ 17
  • 1 ≤ power[i] ≤ 109

Visualization

Tap to expand
Minimum Time to Kill All Monsters INPUT power[] array 3 i=0 1 i=1 4 i=2 Monsters to Defeat: M0 Power: 3 M1 Power: 1 M2 Power: 4 Initial State: mana = 0 gain = 1 ALGORITHM STEPS 1 Use Bitmask DP Track defeated monsters state: 0 to (1 << n) - 1 2 Calculate Days days = ceil(power[i]/gain) gain = popcount(mask) + 1 3 Try All Orders For each undefeated monster Minimize total days 4 State Pruning dp[mask] = min days Skip worse solutions Optimal Order Found: M1 (gain=1): 1 day M0 (gain=2): 2 days M2 (gain=3): 2 days Total: 1+2+2 = 5 attempts FINAL RESULT Day-by-Day Timeline: D1 mana: 0+1=1 [OK] Kill M1 D2 mana: 0+2=2 (need 3) D3 mana: 2+2=4 [OK] Kill M0 D4 mana: 0+3=3 (need 4) D5 mana: 3+3=6 [OK] Kill M2 Days: 1 + 2 + 2 = 5 attempts Accumulation days = 7 total OUTPUT 7 Minimum days to defeat all monsters Key Insight: Bitmask DP with n! permutations pruned to O(n * 2^n). Each state represents which monsters are defeated. The gain increases with each kill, so killing weaker monsters first when gain is low minimizes total days. Formula: days_to_kill(i) = ceil(power[i] / current_gain) where current_gain = number_killed + 1 TutorialsPoint - Minimum Time to Kill All Monsters | Optimized DP with State Pruning
Asked in
Google 45 Amazon 38 Microsoft 32
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen