Count of elements which are second smallest among three consecutive elements | Java implementation of the approach ; Function to return the count of elements P [ i ] such that P [ i ] is the second smallest among P [ i - 1 ] , P [ i ] and P [ i + 1 ] ; To store the required answer ; Traverse from the second element to the second last element ; Return the required answer ; Driver code
class GFG { static int countElements ( int p [ ] , int n ) { int ans = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( p [ i - 1 ] > p [ i ] && p [ i ] > p [ i + 1 ] ) ans ++ ; else if ( p [ i - 1 ] < p [ i ] && p [ i ] < p [ i + 1 ] ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { int p [ ] = { 2 , 5 , 1 , 3 , 4 } ; int n = p . length ; System . out . println ( countElements ( p , n ) ) ; } }