oneby7

1-D Dynamic Programming Take it or skip it

515. Min Cost Climbing Stairs

Easy

A staircase has n steps, numbered 0 to n − 1, and cost[i] is the fee for step i.

You begin on step 0 or on step 1, whichever you like, and getting there is free. Each time you stand on step i, you pay cost[i] and then climb either one step or two. The top of the staircase is just past the last step, at position n. You are done once you reach it.

Return the smallest total fee that gets you to the top.

Example 1

Input: cost = [4, 7, 2, 9, 3, 8]

Output: 9

Explanation: Begin on step 0 and pay 4, climb two to step 2 and pay 2, then climb two to step 4 and pay 3. One more climb of two reaches the top, for 4 + 2 + 3 = 9.

Example 2

Input: cost = [6, 0, 5, 0]

Output: 0

Explanation: Begin on step 1 and pay 0, climb two to step 3 and pay 0, then climb one to the top.

Example 3

Input: cost = [1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 1000000000]

Output: 3000000000

Explanation: Begin on step 1 and stand on steps 1, 3 and 5, paying 109 three times.

Check your understanding

Work out the answer for this input before you write any code.

cost = [3, 1, 4, 1, 5]

Constraints

  • 2 ≤ cost.length ≤ 105
  • 0 ≤ cost[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.