Candy Distribution

Problem

Children stand in a line and each has a rating. Every child gets at least one candy. A child with a higher rating than a neighbour must get more candies than that neighbour. Print the smallest total number of candies.

Constraints

  • 1 <= n <= 10^5

Examples

Input

3
1 0 2

Output

5

Solutions

Best approachTime O(n)Space O(n)

Each rule looks only at one side, so we solve the left rule and the right rule in two separate passes and keep the bigger number for each child. Equal ratings need no extra candies.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Minimum candies.
 * Input   : n, then n ratings.
 * Output  : The total.
 * Approach: Two passes.
 * Time    : O(n)
 * Space   : O(n)
 * 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: Everybody starts with one candy.
        int[] candies = new int[a.length];
        java.util.Arrays.fill(candies, 1);
        // Step 2: Left to right pass: a child with a higher rating than the left neighbour gets one more than that neighbour.
        for (int i = 1; i < a.length; i++) {
            if (a[i] > a[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }
        // Step 3: Right to left pass does the same for the right neighbour. Keep the bigger number.
        for (int i = a.length - 2; i >= 0; i--) {
            if (a[i] > a[i + 1]) {
                candies[i] = Math.max(candies[i], candies[i + 1] + 1);
            }
        }
        long total = 0;
        for (int value : candies) {
            total += value;
        }
        return total;
    }

    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 (1)
  1. Why do we use max in the second pass?