Input: ‘N’ = 3 ‘M’ = 3 ‘POINTS’ = [ [ 1, 4, 3 ], [ 2, 9, 11 ], [ 6, 1, 1 ] ]
Output: 19
The optimal strategy would be:-
Playing the first level in 2nd difficulty mode with 4 points.
Playing the second level in 2nd difficulty mode with 9 points.
Playing the third level in 1st difficulty mode with 6 points.
So we get a total score of 19 points.
First line contains ‘T’, denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ and ‘M’, denoting the number of levels and the number of difficulty modes respectively.
Each of the next ‘N’ lines contains ‘M’ single space-separated integers, elements of 2D array ‘POINTS’.
Return the maximum score that can be obtained on completion of the game.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N, M <= 100
1 <= POINTS[i][j] <= 100
Time Limit: 1 sec
In this approach, we will recursively try out all possible combinations of levels and difficulty modes. A recursive function is called with every difficulty mode for the first level and for the subsequent levels we will try all possible difficulty modes and will choose the one with the maximum score.
At max we will be having three choices at each level which are playing the next level on the same difficulty mode, one mode above, or one mode lower than the current one.
When the ‘LEVEL’ parameter of the recursive function (denoting the current level of the game) crosses the last level we will return zero.
// Recursive function to find maximum score
The recursive approach discussed before can be optimized using memoization. We can memoize the result for each state with a particular ‘LEVEL’ and ‘DIFFICULTY’. In this way, we can save time from recalculating the already calculated results.
For memoization let us define a matrix 2-dimensional array ‘DP’ of size ‘N’ x ‘M’.
DP[i][j] - Maximum score that can be obtained if the game starts from the ith level in jth difficulty mode.
// Recursive function to find maximum score
The idea is the same as memoization. We are going to use the recurrence relation:
DP[i][j] = POINTS[i][j] + min( DP[i+1][j-1], DP[i+1][j], DP[i+1][j+1]). If the difficulty mode mentioned in the recurrence exists in the next level then take that value otherwise take 0.
DP[i][j] - Maximum score that can be obtained if the game starts from the ith level in jth difficulty mode.