📜  java代码示例中的糖果价格hackerearth解决方案

📅  最后修改于: 2022-03-11 14:52:10.932000             🧑  作者: Mango

代码示例1
import java.util.Scanner;

class AliceAndCandy {
    public static void main(String args[]) throws Exception {
        Scanner scan = new Scanner(System.in);
        int length = scan.nextInt();

        int[] children = new int[length];
        int[] candies = new int[length];

        // seed
        children[0] = scan.nextInt();
        candies[0] = 1;

        // search forward sequences
        for (int i = 1; i < length; i++) {
            children[i] = scan.nextInt();
            candies[i] = 1;
            if (children[i] > children[i - 1])
                candies[i] = candies[i - 1] + 1;
        }

        // search reverse sequences
        for (int i = length - 1; i > 0; i--) {
            if (children[i] < children[i - 1])
                candies[i - 1] = Math.max(candies[i - 1], candies[i] + 1);
        }

        long sum = 0;
        for (int i = 0; i < candies.length; i++) {
            sum += candies[i];
        }

        System.out.println(sum);
        scan.close();
    }
}