#2214
Medium Algorithms Minimum health to beat game
Array Greedy
58.9% acceptance
Mar 31, 2026
327
240
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 ith 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_health(damage: Vec<i32>, armor: i32) -> i64 {
let total: i64 = damage.iter().map(|&x| x as i64).sum();
let max_d = *damage.iter().max().unwrap();
let saved = std::cmp::min(max_d, armor) as i64;
total - saved + 1
}
}