Find the peak index of a given array | Java program for the above approach ; Function to find the peak index for the given array ; Base Case ; Check for strictly increasing array ; If the strictly increasing condition is violated , then break ; Stores the value of i , which is a potential peak index ; Second traversal , for strictly decreasing array ; When the strictly decreasing condition is violated , then break ; If i = N - 1 , it means that ans is the peak index ; Otherwise , peak index doesn 't exist ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static int peakIndex ( int [ ] arr ) { int N = arr . length ; if ( arr . length < 3 ) return - 1 ; int i = 0 ; while ( i + 1 < N ) { if ( arr [ i + 1 ] < arr [ i ] arr [ i ] == arr [ i + 1 ] ) break ; i ++ ; } if ( i == 0 i == N - 1 ) return - 1 ; int ans = i ; while ( i < N - 1 ) { if ( arr [ i ] < arr [ i + 1 ] arr [ i ] == arr [ i + 1 ] ) break ; i ++ ; } if ( i == N - 1 ) return ans ; return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 0 } ; System . out . println ( peakIndex ( arr ) ) ; } }