Minimum Health to Beat Game - Problem

๐ŸŽฎ Minimum Health to Beat Game

You're playing an RPG-style game with n levels numbered from 0 to n-1. Each level deals a specific amount of damage to your character, and you must complete all levels in order to win the game.

Given:

  • A damage array where damage[i] represents health lost at level i
  • An armor value that can protect you from damage exactly once

Your goal is to find the minimum starting health needed to survive all levels. Remember:

  • You can use armor on any one level to reduce damage by up to armor points
  • Your health must remain greater than 0 at all times
  • You must complete levels sequentially

Example: If levels deal [3, 5, 2] damage and you have 4 armor, you should use armor on level 1 (damage 5) to minimize starting health needed.

Input & Output

example_1.py โ€” Basic Case
$ Input: damage = [2, 7, 4, 3], armor = 4
โ€บ Output: 13
๐Ÿ’ก Note: Total damage = 16. Use armor on level 1 (damage 7) to reduce by 4. Minimum health = 16 - 4 + 1 = 13.
example_2.py โ€” Armor Exceeds Max Damage
$ Input: damage = [2, 5, 3, 4], armor = 7
โ€บ Output: 10
๐Ÿ’ก Note: Total damage = 14. Max damage is 5, so armor benefit = min(7, 5) = 5. Minimum health = 14 - 5 + 1 = 10.
example_3.py โ€” Single Level
$ Input: damage = [10], armor = 5
โ€บ Output: 6
๐Ÿ’ก Note: Only one level with damage 10. Use armor to reduce by 5. Minimum health = 10 - 5 + 1 = 6.

Constraints

  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค damage[i] โ‰ค 104
  • 0 โ‰ค armor โ‰ค 104
  • Health must remain > 0 at all times

Visualization

Tap to expand
๐ŸŽฎ RPG Health Optimization StrategySTARTHealth: ?LEVEL 1Damage: 3โš”๏ธLEVEL 2Damage: 7๐Ÿ›ก๏ธMAX DMG!LEVEL 3Damage: 4โš”๏ธLEVEL 4Damage: 2โš”๏ธWIN!Health > 0๐Ÿงฎ Calculation Process1. Total Damage = 3 + 7 + 4 + 2 = 162. Maximum Single Damage = max(3, 7, 4, 2) = 73. Armor Value = 4 (given)4. Optimal Armor Benefit = min(armor=4, maxDamage=7) = 45. Use armor on Level 2 (damage 7) โ†’ reduced to 36. Minimum Starting Health = 16 - 4 + 1 = 13
Understanding the Visualization
1
Survey All Levels
Calculate total damage you'll face: sum all damage values
2
Identify Biggest Threat
Find the level with maximum damage - this is where armor will be most effective
3
Calculate Armor Benefit
Armor can reduce damage by at most its value, but can't reduce below 0
4
Optimize Starting Health
Minimum health = Total damage - Maximum armor benefit + 1
Key Takeaway
๐ŸŽฏ Key Insight: Always use armor on the level with highest damage to maximize benefit and minimize required starting health. This greedy approach is optimal because reducing the largest damage gives the maximum overall benefit.
Asked in
Google 42 Microsoft 38 Amazon 35 Meta 28
52.3K Views
High Frequency
~15 min Avg. Time
1.8K 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