Maximum size of sub | C ++ implementation of the approach ; Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver Code ; Print the required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cmp ( int a , int b ) { return ( a > b ) - ( a < b ) ; } int maxSubarraySize ( int arr [ ] , int n ) { int ans = 1 ; int anchor = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int c = cmp ( arr [ i - 1 ] , arr [ i ] ) ; if ( c == 0 ) anchor = i ; else if ( i == n - 1 || c * cmp ( arr [ i ] , arr [ i + 1 ] ) != -1 ) { ans = max ( ans , i - anchor + 1 ) ; anchor = i ; } } return ans ; } int main ( ) { int arr [ ] = { 9 , 4 , 2 , 10 , 7 , 8 , 8 , 1 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubarraySize ( arr , n ) ; }