Advertisement
Fastrail08

Minimum Moves to climb stairs

May 22nd, 2025
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int getMinMoves(int stair, int &n, vector<int> &jumps, vector<int> &memo){
  5.     if(stair == n){
  6.         return 0;
  7.     }
  8.     if(memo[stair] != INT_MAX){
  9.         return memo[stair];
  10.     }
  11.     int minMovesFromStair = INT_MAX;
  12.     //make possible jumps from that stair
  13.     for(int i = 1; i <= jumps[stair]; i++){
  14.         if(stair + i <= n){
  15.             // 1 added as we are jumping from current stair to stair + i
  16.             minMovesFromStair = min(minMovesFromStair, 1 + getMinMoves(stair + i, n, jumps, memo));
  17.         }
  18.     }
  19.    
  20.     return memo[n] = minMovesFromStair;
  21. }
  22.  
  23. int getMinMovesDP(int &n, vector<int> &jumps){
  24.     //Storage & Meaning - The memo array as is, is the DP array
  25.     // Meaning - dp[i] = Min moves from ith stair to nth stair
  26.     vector<int> dp(n + 1, INT_MAX);
  27.    
  28.     //Direction - Smallest Problem at dp[n] - min moves to reach nth stair from nth stair = 0
  29.     //            Largest Problem at dp[0] - min moves to reach nth stair from 0th stair
  30.     dp[n] = 0;
  31.     // Travel & Solve - Travel from smallest subproblem to largest subproblem, by building up the solution'
  32.     for(int i = n - 1; i >= 0; i--){
  33.         for(int j = 1; j <= jumps[i]; j++){
  34.             if(i + j <= n){
  35.                 dp[i] = min(dp[i], 1 + dp[i + j]);
  36.             }
  37.         }
  38.     }
  39.    
  40.     //answer to largest problem
  41.     return dp[0];
  42. }
  43.  
  44. int main() {
  45.     // your code goes here
  46.     int n;
  47.     cin >> n;
  48.     vector<int> jumps(n);
  49.     for(int i = 0; i < n; i++){
  50.         cin >> jumps[i];
  51.     }
  52.     vector<int> memo(n + 1, INT_MAX);
  53.     cout << getMinMoves(0, n, jumps, memo) << '\n';
  54.     cout << getMinMovesDP(n, jumps) << '\n';
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement