It’s an easy problem from leet code 75 with the description being:

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.

Example 1:

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.
Example 2:

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.
Constraints:

2 <= cost.length <= 1000

0 <= cost[i] <= 999

Regarding this problem, you could simply solve with brute force, but doing that would go too many operations, will be slow and cost a lot in terms of processing.

Looking into to this on a different view will help you solve this problem. Instead of trying to check the first indexes and sum up as it go, you can go backwards and add the costs with previous indexes and keep summing up until you get to the beginning and with that you will know the one that will cost less (but you will not know the path that it went).

```
class Solution {
public int minCostClimbingStairs(int[] cost) {
// adding up to previous costs the smallest one
for(int i=cost.length-3;i>-1;i--) {
cost[i] += cost[i+1] < cost[i+2] ? cost[i+1] : cost[i+2];
}
// return smallest one
return cost[0] > cost[1] ? cost[1] : cost[0];
}
}
```

Runtime: 0 ms, faster than 100.00% of Java online submissions for Min Cost Climbing Stairs.

Memory Usage: 43.1 MB, less than 23.26% of Java online submissions for Min Cost Climbing Stairs.

The solution iterate backwards from third last index into 0. On each index it adds the previous costs, considering the smallest one.

At the end (index 0 or 1) it will return the smallest one.

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

## Top comments (0)