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
damagearray wheredamage[i]represents health lost at level i - An
armorvalue 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
armorpoints - 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code