Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children.

Input Format

The first line of the input is an integer N, the number of children in Alice’s class. Each of the following N lines contains an integer that indicates the rating of each child.

Output Format

Output a single line containing the minimum number of candies Alice must buy.

Sample Input

Sample Output


Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int n =sc.nextInt();
        int []r = new int[n];
        for(int i=0; iscore[i]) c[i+1]=c[i]+1;
    for(int i=n-1; i>0; i--){
        if(score[i-1]>score[i]&&!(c[i-1]>c[i])) c[i-1]=c[i]+1;

    for(int i:c) sum+=i;
        return sum+n;


Leave a Reply

Your email address will not be published. Required fields are marked *