Lightoj 1004 Solution in English
Problem Link: Lightoj 1004Click Here to see the discussion in Bangla
Step 1: Understanding the movement
-
The monkey can only move to adjacent cells below the current cell.
-
For example, if the monkey is at
[1,1]
(with 7 bananas), it can go to[2,1]
or[2,2]
. -
Now, which one should it choose? The answer depends on which path eventually gives more bananas.
-
So, we must check all possible paths to know the maximum.
This can naturally be solved using recursion:
-
At each cell, check all possible next moves.
-
Take the path that yields the maximum bananas.
Step 2: Why recursion is not enough
Although recursion works, it will cause a TLE (Time Limit Exceeded).
Why?
Because the monkey can revisit the same cell multiple times from different paths, and each time, recursion will recompute the result for that subproblem.
If you print row/column indices during recursion, you’ll see that many cells are visited multiple times.
Step 3: Adding DP (Memoization)
To avoid recomputing, we use DP (Dynamic Programming):
-
We store the result (maximum bananas from this cell onward) in a DP array.
-
If we reach the same cell again, we don’t recurse further. Instead, we directly return the stored result.
-
This way, each cell is computed only once, making the solution efficient.
Step 4: Special case for diamond shape
Since the array is diamond-shaped, there are two phases:
-
Expanding rows (from top to middle).
-
Contracting rows (from middle to bottom).
That’s why the recursive function uses two conditions for handling movement in different halves of the diamond.
0 comments:
Post a Comment