Start learning free

LESSON 525 OF 674 · DYNAMIC PROGRAMMING

Min Cost Climbing Stairs

Practice O(n)

You get an array cost for a staircase. You pay cost[i] when you stand on step i.

Return the smallest total you can pay to reach the top.

You start on step 0 or step 1, as you like. After you pay for a step, you climb 1 or 2 steps. The top is one step above the last step.

                        ______ top
                  __6__|
            __3__|
      __9__|
__4__|

Example 1:

Input: cost = [4, 9, 3, 6]
Output: 7
Explanation: This is the staircase in the picture.
Start on step 0 and pay 4.
Climb 2 to step 2 and pay 3.
Climb 2 more to reach the top.
In total, 4 + 3 = 7.

Example 2:

Input: cost = [5, 0]
Output: 0
Explanation: Start on step 1 and pay 0.
Climb 1 to reach the top.
The 5 on step 0 is never paid.

Example 3:

Input: cost = [2, 7, 1, 1, 8, 3, 2]
Output: 7
Explanation: Stand on steps 0, 2, 3 and 5.
That costs 2 + 1 + 1 + 3 = 7.
From step 5, climbing 2 reaches the top.

Constraints:

  • cost has 2 to 1,000 steps.
  • Each cost is from 0 to 999.

STEP 1 OF 3
    Ctrl + Enter to check