joshita / dev

Published

- 2 min read

Min cost to climb stairs problem dynamic programming

img of Min cost to climb stairs problem dynamic programming

Min cost to climb stairs Dynamic Programming Problem

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor

  1. Why this is a dp problem - because we are asked to minimize the cost to climb stairs, at each step/index we would be doing minimum
  2. There are 2 paths to take in this problem, total cost will be current stair cost + min(i-1, i-2) thinking that you are calculating the cost to stand at current stair
  3. During recursion we would be able to get cost of standing at i-1, i-2 and get the minimum such that we plan to climb any of it
  4. Hand drawn diagram to expplain the recursion
       System.out.println(cbS.climbingStairs(arr, arr.length-1, dp)); //starting recursion from end

    private int climbingStairs(int arr[], int n, int dp[]) {
        if(n < 0){
            System.out.println("We hit here!");
            return 0;
        }
        if(n==0 || n ==1){ //base condition
            dp[n] = arr[n];
            return dp[n];
        }
        if(dp[n] >= 0) {  //this condition will prevent us from going to the dp without a value
            return dp[n];
        }
        int cost = arr[n] + Math.min(climbingStairs(arr, n-1, dp), climbingStairs(arr, n-2, dp));
        dp[n] = cost;
        return cost;
    }