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
def Count_Segment ( p , n ) : NEW_LINE INDENT count = 0 NEW_LINE upto = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if p [ i ] > p [ i - 1 ] and p [ i ] > p [ i + 1 ] : NEW_LINE INDENT curr = p [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and p [ j ] < curr : NEW_LINE INDENT upto [ p [ j ] ] = curr NEW_LINE j -= 1 NEW_LINE DEDENT j = i + 1 NEW_LINE while j < n and p [ j ] < curr : NEW_LINE INDENT if upto [ curr - p [ j ] ] == curr : NEW_LINE INDENT count += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = [ 3 , 4 , 1 , 5 , 2 ] NEW_LINE n = len ( p ) NEW_LINE print ( Count_Segment ( p , n ) ) NEW_LINE DEDENT