min-cost-climbing-stairs.sh — zsh
dynamic-programmingarrays

Given an integer array cost where cost[i] is the toll charged when you step off stair i, return the minimum total toll to reach the top of the floor.

You can start from stair 0 or stair 1, and from any stair you may climb either one or two stairs. Reaching "the top" means stepping beyond the last stair.

Input / output

  • Input: cost: int[]
  • Output: int (minimum total toll)

Examples

  1. cost = [10,15,20] returns 15 because starting at stair 1 and paying 15 climbs straight to the top.
  2. cost = [1,100,1,1,1,100,1,1,100,1] returns 6 by hopping over every stair that charges 100.
  3. cost = [5,10] returns 5 because you start on stair 0, pay 5, and climb two stairs to the top.

Constraints

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999

Follow-up Can you solve it with O(1) extra space by keeping only the two most recent subresults instead of a full DP array?

Examples
Example 1
Input: cost = [10,15,20]
Output: 15
Example 2
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Example 3
Input: cost = [5,10]
Output: 5