[Java] 746. Use the least cost to climb the stairs ---- predict the future, go step by step in reverse order! ! !

Each index of the array is used as a ladder, and the i-th ladder corresponds to a non-negative physical cost value cost i .

Every time you climb a ladder, you have to spend the corresponding physical cost value, and then you can choose to continue climbing one ladder or climbing two ladders.

You need to find the lowest cost to reach the top of the floor. At the beginning, you can choose the element with index 0 or 1 as the initial ladder.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: The minimum cost is to start from cost[1], and then take two steps to reach the top of the ladder, a total cost of 15.
Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: The lowest cost method is to start from cost[0], go through the 1s one by one, skip cost[ 3], it costs a total of 6.
note:

The length of cost will be [2, 1000].
Each cost[i] will be an Integer type with a range of [0, 999].

public static int minCostClimbingStairs(int[] cost) {
    
    
		if(cost.length==0) {
    
    
			return 0;
		}
		if(cost.length==1) {
    
    
			return cost[0];
		}
		for(int i=2;i<cost.length;i++) {
    
    
			cost[i]+=Math.min(cost[i-1],cost[i-2]);
		}
		return Math.min(cost[cost.length-1],cost[cost.length-2]);

    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/111466862