O(1) space - Simple modification to 'Climb Stairs'


  • 0
    N

    This problem is a slightly modified version of the famous Google problem (now banned) 'Climb Stairs: https://leetcode.com/problems/climbing-stairs/description/

    class Solution {
        public int minCostClimbingStairs(int[] a) {
            int n = a.length; 
            
            int prevPrev = a[0], prev = a[1];
            
            for (int i = 2; i < n; i++) {
                int cur = a[i] + Math.min(prev, prevPrev);
                prevPrev = prev;
                prev = cur;
            }
            
            //This is the modification
            return Math.min(prev, prevPrev);
        }
    }
    

  • 0
    K

    Simple solution.
    Problem statement says: cost will have a length in the range [2, 1000]
    So you can avoid the n==0 & n<2 checks


  • 0
    N

    @k_j yes, I overlooked that. Thanks!


  • 0
    C

    Can you please explain the solution. I am having a hard time understanding.


Log in to reply
 

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