#K311. Find Peak Element
Find Peak Element
Find Peak Element
Given an array of integers, your task is to find the index of any peak element. A peak element is defined as an element that is strictly greater than its neighbors. For the first and last elements, only one adjacent neighbor exists, and they are considered peaks if they are greater than that neighbor.
If there is no peak element in the array, output -1.
Note: The input is provided via standard input (stdin) and the result should be printed to standard output (stdout). The array is zero-indexed.
The problem may have multiple valid answers if there is more than one peak element. However, use the following approach:
- If the first element is greater than its neighbor, return index 0.
- If the last element is greater than its neighbor, return the last index.
- Otherwise, return the index of the first encountered element which is strictly greater than both of its neighbors.
- If no such element exists, return -1.
inputFormat
The input consists of two lines:
- The first line contains a single integer
n
, which represents the number of elements in the array. - The second line contains
n
space-separated integers representing the elements of the array.
Input is provided via stdin.
outputFormat
Output a single integer to stdout — the index of any peak element. If no peak element exists, output -1
.
4
5 3 2 1
0