Create an array maxfromEnd
for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT maxFromEnd [ i ] = max ( maxFromEnd [ i + 1 ] , v [ i ] ) ; NEW_LINE DEDENT result = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT low = i + 1 ; high = n - 1 ; ans = i ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) ; NEW_LINE if ( v [ i ] <= maxFromEnd [ mid ] ) : NEW_LINE DEDENT DEDENT