cswork / OAOpen practice workspace

MetaOA #17

Find Peak Element

Estimated MediumJudge-ready

Topics (AI-labelled)Binary Search

A peak is strictly greater than its neighbors, and the positions beyond both ends of the array count as negative infinity. Adjacent elements are guaranteed to be different. Return the 0-based index of any peak; if there are several peaks, any one of them is correct. O(log n) time is required.

Input

The first line contains n (1..1000); the second line contains n integers (−2147483648..2147483647), with adjacent numbers different.

Output

Output the 0-based index of any valid peak; it does not have to be the same peak chosen in the example.

Example 1

Input:

4
1 2 3 1

Output:

2

Example 2

Input:

5
1 3 1 3 1

Output:

1

Example 3

Input:

1
-2147483648

Output:

0

Example notes

Example 1: the 3 at index 2 is greater than its neighbors 2 and 1, so the output is 2.

Example 2: the values at indices 1 and 3 are both 3, each strictly greater than the 1s on both sides; outputting either 1 or 3 is accepted.

Example 3: the only element is greater than the positions on both sides, which count as negative infinity, so index 0 is valid even if that element is the smallest 32-bit integer.

Editorial

Loading solution…