The problem I have, I managed to solve recursively, but I wish for a more optimal solution that would use memoization, but I am not skilled enough to know how it should work in this context.
The problem:
There is an 2d array with random positive integers, and you are given a random amount of moves. You start moving from the top left corner, and the only moves you are allowed to make are:
left
right
down
You need to end at the bottom row and collect as much as you can on your way. You cannot revisit a position.
Memoization is about storing values and building the future results on this, but since there are so many paths one can take, how do I use it? Is it even memoization that I should use or have I made a wrong guess 🙂 ?
This is basically a dynamic programming problem. You don’t really have to consider all the possible paths at each step since the details of the paths don’t affect future decisions. For each cell, you need to know the maximum amount that can be collected if you go a particular direction and taking a particular number of moves. Nothing else affects your decisions.
If bestAmount is memoized, then you get a fairly efficient solution since the number of possibilities is relatively limited.
Treating it as a dynamic programming problem will get you an even more efficient solution though.