Welcome back.
So this is the recursive solution that we had previously written.
Now let's go ahead and memorize this.
And you will see that.
To do that we will just be adding a few lines of code okay.
So let me add a memory over here.
And this array will have the size n okay.
Where n is the length of the cost array.
And initially we will fill this array with the value minus one at every index in this array.
Now in the helper function after the base case, before we go ahead and get into the recursive case,
which is what we have written over here, first we will go and check whether memo at index is not equal
to minus one.
So if memo at index.
Is not equal to minus one, then it would mean that we had already previously computed it and stored
it in the memory.
And that's why it is not equal to minus one.
Because notice initially we had filled every index in the memo array with the value minus one.
So again over here if this is not minus one it is because we have computed and stored a particular value
at that particular index.
And therefore we do not need to recompute this.
But rather we will just return memo at index okay.
Now if this is not the case then these two steps are as it is.
We will go ahead and calculate one and two.
And then before we return over here we will store the value.
So we will say memo at index is equal to whatever we have over here which is math dot min between 1
and 2.
So let us put that over here.
And then we can just return memo at index.
So that's it.
Now notice that we just added a few lines of code to convert the recursive approach to the memoization
approach.
Now let's go ahead and run this code and see if it's passing all the test cases.
And you can see that it's passing all the test cases.