Back
Leetcode Problems
Array
1D Array2D Array3D ArrayBinary Search
Strings
1D Array2D Array3D ArrayBinary Search
Trees
Introduction to TreesTree Problems
Dynamic programming
1d dp problems2d dp problems
loading image

Please wait a little bit, we are fetching the blogs from the database ....

Back

title: 'DP problem set-3' topic : 'dynamic-programming' id: 3 description: 'Dynamic programming problem set of 2D dp. problems - Ninja’s Training and Unique Paths' subtopic: ['2d-dp']

DP problem set - 3

Summary for the blog ⌨️⌨️ In this blog of Dynamic programming, we will discuss 2d dp problems, we will see how to tackle these problems, intuition and the codes.

Sl NoLeetcode problems/ AlgorithmsLink
1Ninja’s TrainingProblem 1
2Unique PathsProblem 2

Problem No - 1 [Ninja’s Training]

🧑🏽‍💻 Problem statement

Ninja is planing this ‘N’ days-long training schedule. Each day, he can perform any one of these three activities. (Running, Fighting Practice or Learning New Moves). Each activity has some merit points on each day. As Ninja has to improve all his skills, he can’t do the same activity in two consecutive days. Can you help Ninja find out the maximum merit points Ninja can earn?

You are given a 2D array of size N*3 ‘POINTS’ with the points corresponding to each day and activity. Your task is to calculate the maximum number of merit points that Ninja can earn.

Example :

For the array - [[1,2,5], [3 ,1 ,1] ,[3,3,3] ]

the answer will be 11 as 5 + 3 + 3.

Intuition :-

  • Here the aim is to maximize the merit points of the ninja. you may think of solving the problem with a greedy approach, but it would fail (since grabbing maximum credit points in a day would not give up the maximum it can attain ).
  • Hence we should try out all possible combination and determine the maximum among them, trying all possible ways means a recursive way,
  • We will iterate the array in the recursion with a index i from 0 to n th index, where n is the number of days(ie no of rows). and also we would maintain a variable ‘prev’ to track the task done in previous day. at every index we can try 2 tasks (one excluding the previous days task).
  • initially the prev would be set to 3, indicating no previous task is performed at day 0.
  • The base case would be if we reach index n we would return 0 (since we reached index n and there is no more days left to train).
  • Since the time complexity is 2^n and space complexity if O(n), we would need to optimize it, we will use a technique called memoisation to optimize it.
  • In memoisation we will take a 2D array of size nx4 (since prev can take values 0,1,2,3) to store the maximum merit points calculated in a day with a corresponding previous days task.
  • you can explore other technique called tabulation as well.
#include<bits/stdc++.h>
int solve(int i,int n,int prev,vector<vector<int>> &points,vector<vector<int>>&dp){
    if(i==n) return 0;

    int maxi=INT_MIN;
    if(dp[i][prev]!=-1) return dp[i][prev];
    for(int j=0;j<3;j++){
        if(j!=prev){
        int temp =points[i][j]+ solve(i+1, n, j, points,dp);
        maxi=max(maxi,temp);
        }
    }
    return dp[i][prev]= maxi;
}
int ninjaTraining(int n, vector<vector<int>> &points)
{
    // Write your code here.
    int prev =3;
    vector<vector<int>>dp(n,vector<int>(4,-1));
    return solve(0,n,prev,points,dp);
}

Problem No - 2 [Unique Paths]

🧑🏽‍💻 Problem statement

You are present at point ‘A’ which is the top-left cell of an M X N matrix, your destination is point ‘B’, which is the bottom-right cell of the same matrix. Your task is to find the total number of unique paths from point ‘A’ to point ‘B’.In other words, you will be given the dimensions of the matrix as integers ‘M’ and ‘N’, your task is to find the total number of unique paths from the cell MATRIX[0][0] to MATRIX['M' - 1]['N' - 1].

To traverse in the matrix, you can either move Right or Down at each step. For example in a given point MATRIX[i] [j], you can move to either MATRIX[i + 1][j] or MATRIX[i][j + 1].

For example:

For the two test cases given below (m and n are given for each test case) -

2 2
1 1

the output is

2 1

Explanation of Sample Output 1:

In test case 1, we are given a 2 x 2 matrix, to move from matrix[0][0] to matrix[1][1] we have the following possible paths.

Path 1 = (0, 0) -> (0, 1) -> (1, 1) Path 2 = (0, 0) -> (1, 0) -> (1, 1)

Hence a total of 2 paths are available, so the output is 2.

In test case 2, we are given a 1 x 1 matrix, hence we just have a single cell which is both the starting and ending point. Hence the output is 1.

Intuition :-

  • Here the problem is very simple, we just need to travel from (0,0) to (m-1,n-1). and the only move possible is down and right.
  • we would solve this in a recursive way. we will take two variable i and j initialized to 0.
  • The base case would be - → i==m-1 and j==n-1 , then we would return 1. → i≥m or j≥n then we would return 0.
  • In every index we have 2 possibilities , ie either go down or go right.
  • We would return the sum of both the possibilities, as we are asked to count the number of ways.
  • memoisation technique similar to previous problem is implimented.
#include <bits/stdc++.h>
int solve(int i, int j, int m, int n, vector<vector<int>> &dp) {
  if (i == m - 1 && j == n - 1)
    return 1;
  if (i >= m || j >= n)
    return 0;

  if (dp[i][j] != -1)
    return dp[i][j];
  int right = solve(i, j + 1, m, n, dp);
  int down = solve(i + 1, j, m, n, dp);

  return dp[i][j] = right + down;
}
int uniquePaths(int m, int n) {
  // Write your code here.
  vector<vector<int>> dp(m, vector<int>(n, -1));
  return solve(0, 0, m, n, dp);
}

: Hey! is your brain fried of this blog? . Well what about a game with me?