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.
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.The total cost is 6.
2 <= cost.length <= 10000 <= cost[i] <= 999Start by identifying that you can reach step i from either step i-1 or i-2. This gives rise to a recursive relation where the cost to reach the i-th step is the cost of the step itself plus the minimum of the costs to reach the two preceding steps.
To optimize the recursive solution, we can store the results of subproblems (i.e., costs for each step) and reuse them instead of solving the same subproblems repeatedly.
Iteratively build up the solution from the base cases (steps 0 and 1) to the target steps, avoiding recursion overhead.
Instead of maintaining an array for dynamic programming, we only need to keep track of the last two costs since the cost to reach each step depends only on the two preceding steps.