Find the peek index of the valid mountain array.
Note: Array must be a mountain array
Example
Input: arr[] = { 3, 4, 5, 1 };
Output: 2
Approach: Binary search
Java
public class PeakIndex {public static void main(String[] args) {int arr[] = { 3, 4, 5, 1 };int index = peakIndexInMountainArray(arr, 0, arr.length - 1);System.out.println(index);}public static int peakIndexInMountainArray(int[] arr, int low, int high) {// calculate midint mid = low + (high - low) / 2;// base caseif (mid == 0 || mid == arr.length - 1)return mid;// if mid before less and greater lessif (arr[mid - 1] < arr[mid] && arr[mid + 1] < arr[mid])return mid;// call again binary searchif (arr[mid] > arr[mid - 1]) {return peakIndexInMountainArray(arr, mid, high);} elsereturn peakIndexInMountainArray(arr, low, mid);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the peak//element index in the array//of valid mountain arrayint peakIndexInMountainArray(int arr[],int n){int low=0,high=n-1;int mid=0;while(low<high){mid=low+(high-low)/2;//if mid is last or first then return//midif(mid==0||mid==n-1)return mid;//if mid element is greater than left//and right then return midif(arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1])return mid;//if mid greter then left and mid less//than right move low to midif(arr[mid]>arr[mid-1]&&arr[mid]<arr[mid+1])low=mid;//else move high to midelsehigh=mid;}return mid;}int main(){int arr[] = { 3, 4, 5, 1 };int n=sizeof(arr)/sizeof(arr[0]);int index = peakIndexInMountainArray(arr,n);cout<<index;return 0;}
No comments:
Post a Comment