Pretty simple O(n) time, O(1) space java dp solution


  • 0
    Y
    class Solution {
        public int minCostClimbingStairs(int[] cost) {
            int first = 0;
            int second = 0;
            int res = 0;
            for(int i = 2; i <= cost.length; i ++) {
                res = Math.min(first + cost[i - 2], second + cost[i - 1]);
                first = second;
                second = res;
            }
            return res;
        }
    }
    

    Normal O(n) space solution:

    class Solution {
        public int minCostClimbingStairs(int[] cost) {
            int[] dp = new int[cost.length + 1];
            for(int i = 2; i < dp.length; i ++) {
                dp[i] = Math.min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]);
            }
            return dp[cost.length];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.