Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The least starting health

Hard · Target 30 minutes · Dynamic programming · Type asked atGoogleAmazon

A knight starts at the top-left cell of a grid and must reach the bottom-right cell, moving only right or down. Each cell changes his health by its value (negative cells hurt, positive cells heal), including the first and last cells. If his health ever drops to 0 or below, he dies. Return the least positive starting health that lets him arrive alive.

Examples

InputOutputWhy
dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]7Right, right, down, down: health 7 → 5 → 2 → 5 → 6 → 1.
dungeon = [[0]]1Health must start positive.
dungeon = [[-10]]11He needs 11 to survive losing 10.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • −1000 ≤ dungeon[r][c] ≤ 1000

Hints

Hint 1

Going forwards, you would need to track both health and the lowest point reached: two things to optimise at once.

Hint 2

Going backwards, need[r][c] = the least health on entering (r, c) that guarantees survival from there.

Hint 3

need[r][c] = max(1, min(need below, need right) − dungeon[r][c]).

Where people lose marks

  • Filling forwards with the maximum health so far, which ignores dips along the way.
  • Forgetting the max with 1, so a large heal later "pays for" dying earlier.
  • Not applying the start cell's own value.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.