This problem really got me thinking, at first glance problem seems pretty do-able, but after two wrong submissions, I realized, my dynamic programming (DP) state is completely wrong! Finally when I solved it, it made my day.

If you haven’t tried, do so. You’ll have fun.


OK, straight forward, the question doesn’t ask us to maximize Harry’s path value. We must make sure he is alive! (😛). The question is to assign minimum amount of strength at the beginning of the grid so that Harry can choose a path and collect the Sorcerer’s stone (while being alive, this seems redundant). The regular DP — maximizing the path value doesn’t work. Here’s an example, suppose the grid is

So Harry starts with 1/0 strength (hypothetical), then either path he takes, his strength decreases (<=0) and he dies. So we must assign him a minimum strength of 2.

The DP state is surprisingly simple, suppose we are at the cell (r-1,c-1) and we want to go to (r,c). For Harry to be alive, it is sufficient for him to end up at (r,c) with resultant strength ‘1’. So we choose the path that maximizes Harry’s strength (alternately if negative values, we choose the one which decreases his strength least).

Suppose that the cell values are in `s[1…..r][1….c]`

Initialization — last row:

for other rows and columns:

Artificial Intelligence Researcher | Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store