Skip to main content

Peak Index in a Mountain Array

Question

Given an array A of integers, find the index of the peak element in the array A and return its index. An array A is defined as a mountain if it meets the following conditions:

  1. A[0] < A[1]
  2. A[A.length - 2] > A[A.length - 1]
  3. There exists some i with 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

Write a function that takes an array A of integers and returns the index of the peak element in the array A. If the peak element does not exist, return -1.

Example 1
Input: [0,1,0] 
Output: 1

Solution

all//Peak Index in a Mountain Array.py


def peakIndexInMountainArray(A):
for i in range(len(A)):
if A[i] > A[i+1]:
return i
return -1