Implement the minimumCostToClimb method that finds the minimum cost needed to reach the top of the stairs.

The input contains an array cost and its length size. Each value represents the cost of stepping on that stair. You may start from step 0 or step 1, and from any step you may climb either one or two steps.

Your task is to return the minimum total cost required to reach the top, which is just after the last stair. For example, for [10,15,20], starting from step 1 costs 15 and reaches the top with the minimum cost.

Example 1

Input
cost (int[]) = [10,15,20]
size (int) = 3
Returns (int) 15

Example 2

Input
cost (int[]) = [1,100,1,1,1,100,1,1,100,1]
size (int) = 10
Returns (int) 6

Example 3

Input
cost (int[]) = [5,10]
size (int) = 2
Returns (int) 5

This problem can be solved by keeping the minimum cost needed to reach each stair.

For a stair i, you can arrive from stair i - 1 or stair i - 2. So the best cost for stair i is its own cost plus the smaller cost of those two previous positions.

After processing all stairs, the top can be reached from either of the last two stairs, so return the smaller of those two costs.

Pseudocode:

function minimumCostToClimb(cost, size):
    if size == 0:
        return 0
    if size == 1:
        return cost[0]
    first = cost[0]
    second = cost[1]
    for i from 2 to size - 1:
        current = cost[i] + min(first, second)
        first = second
        second = current
    return min(first, second)
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.