741. Cherry Pickup

Problem

Intuition

The initial intuition was to travel from (0,0) to (N-1, N-1) in the best possible path and do the reverse i.e. travel from (N-1, N-1) to (0,0) in the best possible path. Combining these two best paths would give me the solution.

But that won't give right solution all the time. That is because when we travel from top to bottom we modify the grid, i.e. whenever we get the cherry we convert it into 0. So the travel from (N-1, N-1) to (0,0), might not always get the best path as the grid is modified.

For interview purposes, if you do not know the below intuition it is almost impossible to arrive at correct solution, (not even optimised solution).

The next level of intuition is we need to check the paths simultaneously. That is traversing the grid in all possible ways from top-left and bottom-right. But this will also end up like the above first mentioned intuition as to avoid double counting, we need to keep modifying the grid.

Then the next level of intuition is we can start two pointers from start grid and reach till the end. This ensures that all the possible states are checked at single go. Double counting can be easily avoided adding one condition. This way we can make sure we are taking the best possible path at every iteration.

There can be space optimised version for this, but for a 45 minute interview, if we come up with above approach, it is an achievement in itself.

Time Complexity

Space Complexity

Solution

Last updated