Complete-Preparation

šŸŽ‰ One-stop destination for all your technical interview Preparation šŸŽ‰

View the Project on GitHub

746. Min Cost Climbing Stairs šŸŒŸ

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.

Recursive Solution (TLE)

Code


class Solution {
private:
    int minCost(vector<int>& cost, int n)
    {
        if (n == 0 || n == 1) return cost[n];
        return cost[n] + min(minCost(cost, n - 1), minCost(cost, n - 2));
    }

public:
    int minCostClimbingStairs(vector<int>& cost)
    {
        int n = cost.size();
        return min(minCost(cost, n - 1), minCost(cost, n - 2));
    }
};

Memoization (Top-Down) (3ms-AC)

Code

class Solution {
private:
    int minCost(vector<int>& cost, vector<int>& memo, int n)
    {
        if (n == 0 || n == 1) return cost[n];
        if (memo[n] != -1) return memo[n];
        return memo[n] = cost[n] + min(minCost(cost, memo, n - 1), minCost(cost, memo, n - 2));
    }

public:
    int minCostClimbingStairs(vector<int>& cost)
    {
        int n = cost.size();
        vector<int> memo(n + 1, -1);
        return min(minCost(cost, memo, n - 1), minCost(cost, memo, n - 2));
    }
};

Tabulation (Bottom-Up) (7ms-AC)

Code

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost)
    {
        int n = cost.size();
        vector<int> dp(n + 1);
        dp[0] = cost[0];
        dp[1] = cost[1];
        for (int i = 2; i < n; i++) {
            dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]);
        }
        return min(dp[n - 1], dp[n - 2]);
    }
};

Reduced space complexity

Code

class Solution {
private:
public:
    int minCostClimbingStairs(vector<int>& cost)
    {
        int first = cost[0];
        int second = cost[1];

        for (auto currCost : cost) {
            int curr = currCost + min(first, second);
            first = second;
            second = curr;
        }
        return min(first, second);
    }
};