Candies by Rating

medium greedy arrays 1000 ms · 256 MB

Candies by Rating

n children stand in a row, numbered 1 to n from left to right. Child i has a rating r_i.

You hand out candies so that both rules hold:

  • every child gets at least one candy;
  • if two children stand next to each other and one has a strictly higher rating than the other, the one with the higher rating gets strictly more candies.

Neighbours with equal ratings are not constrained in any way relative to each other.

Find the minimum total number of candies you need.

Input

The first line contains an integer n (1 ≤ n ≤ 2·10^5).

The second line contains n integers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9).

Output

Print one integer: the minimum total number of candies.

Notes

In the first example the children can get 2, 1, 2 candies: the middle child has the lowest rating, and each of the outer children beats it, so each needs at least 2. The total is 5.

In the second example an optimal distribution is 1, 2, 3, 1, 3, 2, 1. The two children with rating 3 stand next to each other, so the second of them can get a single candy even though the first gets 3. The total is 13.

The answer can exceed 2^31, so use a 64-bit integer type.

Example 1

Input

3
4 1 7

Output

5

Example 2

Input

7
1 2 3 3 5 2 1

Output

13

Hints · reveal one at a time if you're stuck

Hint 1

Each rule only compares two neighbours, so look at the rising and falling stretches of ratings separately. A child on a stretch that keeps going up must have more candies than everyone before it on that stretch. What is the smallest number of candies that such a child can be forced to get?

Hint 2

Measure, for each child, the length of the strictly increasing run that ends at it when scanning from the left, and the strictly decreasing run that starts at it when scanning from the right. Equal neighbours break a run, since they have no constraint between them.

Hint 3

Each child needs at least the larger of its two run lengths, and giving every child exactly that amount satisfies all the rules. Work out why a child with a higher rating than a neighbour always gets strictly more, and then add up the amounts, remembering that the total can be large.

report an issue Prefer your own editor? sooks prep 52 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.