Skip to the content

The health bar

Problem

In Pixelia, a potion never fills the health bar past its top: whatever is left over is lost. The hero starts with a full bar, and every turn either takes a hit or drinks a potion.

Write a function that takes top (an integer, 1 or more) and changes, a list of integers (negative is a hit, positive is a potion; it may be empty). Apply the changes in order: add each one to the health and, if it goes over top, set it back to top in that same step. Return the index of the change that brings health to 0 or less, or -1 if that never happens. Indexes start at 0, and whatever comes after does not matter. With 10 and [-4, 8, -7, -3], health goes 6, then 14 which stays at 10, then 3, then 0. Reaching 0 already counts as falling: return 3. Without capping at every step, it would have ended at 4 and survived.

Examples

  • The example

    10, [-4, 8, -7, -3] → 3

  • Survives

    20, [-5, -5, 3, -10] → -1

  • Drops below 0, then heals

    5, [-2, -4, 6] → 1

  • A potion with a full bar

    8, [5, -8] → 1

  • Two wasted potions

    10, [-3, 5, 5, -9, -2] → 4

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def fatal_hit(top, changes):
    pass

JavaScript

function fatalHit(top, changes) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →