Overview
This is a direct variation of the classic Fibonacci sequence or "Climbing Stairs" problem, but instead of counting ways, we are minimizing cost.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Pay the cost to climb one or two steps to reach the top.
This is a direct variation of the classic Fibonacci sequence or "Climbing Stairs" problem, but instead of counting ways, we are minimizing cost.
`dp[i]` represents the minimum cost to REACH step `i`. Notice it's the cost to reach it, not the cost to leave it.
To reach step `i`, you either came from step `i-1` (and paid `cost[i-1]`) or you came from step `i-2` (and paid `cost[i-2]`). Take the minimum.
Since `dp[i]` only depends on `dp[i-1]` and `dp[i-2]`, we only need two variables to track the state, reducing space complexity to O(1).