Minimum Health to Beat Game - Problem

You are playing a game that has n levels numbered from 0 to n - 1. You are given a 0-indexed integer array damage where damage[i] is the amount of health you will lose to complete the i-th level.

You are also given an integer armor. You may use your armor ability at most once during the game on any level which will protect you from at most armor damage.

You must complete the levels in order and your health must be greater than 0 at all times to beat the game.

Return the minimum health you need to start with to beat the game.

Input & Output

Example 1 — Basic Case
$ Input: damage = [2,7,4,3], armor = 4
Output: 13
💡 Note: Use armor on level 1 (damage 7), reducing it to 3. Total damage becomes [2,3,4,3]. To maintain health > 0 throughout: start with 13, after levels: 13→11→8→4→1. Minimum health needed is 13.
Example 2 — High Armor Value
$ Input: damage = [2,5,3,4], armor = 7
Output: 10
💡 Note: Use armor on level 1 (damage 5), reducing it to 0. Total damage becomes [2,0,3,4]. Starting with 10 health: 10→8→8→5→1. Minimum health needed is 10.
Example 3 — Small Armor
$ Input: damage = [3,3,3], armor = 1
Output: 9
💡 Note: Use armor on any level to reduce one 3 to 2. Total damage becomes [2,3,3]. To maintain health > 0 throughout: start with 9, after levels: 9→7→4→1. Minimum health needed is 9.

Constraints

  • n == damage.length
  • 1 ≤ n ≤ 105
  • 0 ≤ damage[i] ≤ 106
  • 0 ≤ armor ≤ 106

Visualization

Tap to expand
Minimum Health to Beat Game INPUT damage array: 2 i=0 7 i=1 4 i=2 3 i=3 armor value: 4 ARMOR damage=[2,7,4,3], armor=4 ALGORITHM STEPS 1 Calculate Total Sum all damage values 2+7+4+3 = 16 2 Find Max Damage Identify largest hit max(2,7,4,3) = 7 3 Apply Armor Use on max, cap at armor min(7, 4) = 4 saved 4 Compute Min Health total - saved + 1 16 - 4 + 1 = 13 Formula: saved = min(max_dmg, armor) health = total - saved + 1 FINAL RESULT Level Progression with Armor: Lvl 0 -2 Lvl 1 -3 Lvl 2 -4 Lvl 3 -3 ARMOR USED (7-4=3) Calculation: Total damage: 16 Armor saves: -4 Stay alive: +1 Min health: 10 Output: 10 OK Key Insight: The greedy strategy is to use armor on the level with MAXIMUM damage to minimize total health needed. If max damage exceeds armor, we save exactly 'armor' HP. Otherwise, we save the full max damage. We need +1 extra HP because health must be GREATER than 0 (not equal to 0) to survive. TutorialsPoint - Minimum Health to Beat Game | Greedy Approach
Asked in
Amazon 15 Google 12
32.0K Views
Medium Frequency
~25 min Avg. Time
890 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