Count index pairs which satisfy the given condition | Function to return the count of required index pairs ; To store the required count ; Array to store the left elements upto which current element is maximum ; Iterating through the whole permutation except first and last element ; If current element can be maximum in a subsegment ; Current maximum ; Iterating for smaller values then current maximum on left of it ; Storing left borders of the current maximum ; Iterating for smaller values then current maximum on right of it ; Condition satisfies ; Return count of subsegments ; Driver Code
function Count_Segment ( p , n ) { var count = 0 ; var upto = Array ( n + 1 ) . fill ( 0 ) ; for ( i = 0 ; i < n + 1 ; i ++ ) upto [ i ] = 0 ; var j = 0 , curr = 0 ; for ( i = 1 ; i < n ; i ++ ) { if ( p [ i ] > p [ i - 1 ] && p [ i ] > p [ i + 1 ] ) { curr = p [ i ] ; j = i - 1 ; while ( j >= 0 && p [ j ] < curr ) { upto [ p [ j ] ] = curr ; j -= 1 ; } j = i + 1 ; while ( j < n && p [ j ] < curr ) { if ( upto [ curr - p [ j ] ] == curr ) count += 1 ; j += 1 ; } } } return count ; } var p = [ 3 , 4 , 1 , 5 , 2 ] ; var n = p . length ; document . write ( Count_Segment ( p , n ) ) ;