Minimum Cost Climbing Stairs

Problem

cost[i] is the price of standing on step i. After paying you may climb one or two steps. You may start on step 0 or step 1. Print the least total price to get past the last step (the top). At least two steps exist.

Constraints

  • 2 <= n <= 1000
  • 0 <= cost[i] <= 999

Examples

Input

3
10 15 20

Output

15

Solutions

Best approachTime O(n)Space O(1)

Only the last two answers are needed to compute the next one, so two variables replace the table. O(n) time and O(1) memory.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Climb stairs cheaply.
 * Input   : n, then n costs.
 * Output  : Least total price.
 * Approach: Two variables.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Keep only the best cost to stand on the last two steps. "second" is step i - 2, "first" is step i - 1.
        long second = a[0];
        long first = a[1];
        for (int i = 2; i < a.length; i++) {
            // Step 2: To stand on step i, pay a[i] and come from the cheaper of the last two steps.
            long current = a[i] + Math.min(first, second);
            second = first;
            first = current;
        }
        // Step 3: The top can be reached from either of the last two steps.
        return Math.min(first, second);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (2)
  1. From which steps can we stand on step i?
  2. Why can the top come from the last two steps?