Split an array into minimum number of non | C ++ program for the above approach ; Function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; Initialize variable to keep track of current sequence ; Stores the required result ; Traverse the array , arr [ ] ; If current sequence is neither non - increasing nor non - decreasing ; If previous element is greater ; Update current ; If previous element is equal to the current element ; Update current ; Otherwise ; Update current ; If current sequence is in non - decreasing ; If previous element is less than or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; If current sequence is Non - Increasing ; If previous element is greater or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; Print the answer ; Driver Code ; Given array ; Given size of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSubarrays ( int arr [ ] , int n ) { char current = ' N ' ; int answer = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( current == ' N ' ) { if ( arr [ i ] < arr [ i - 1 ] ) { current = ' D ' ; } else if ( arr [ i ] == arr [ i - 1 ] ) { current = ' N ' ; } else { current = ' I ' ; } } else if ( current == ' I ' ) { if ( arr [ i ] >= arr [ i - 1 ] ) { current = ' I ' ; } else { current = ' N ' ; answer += 1 ; } } else { if ( arr [ i ] <= arr [ i - 1 ] ) { current = ' D ' ; } else { current = ' N ' ; answer += 1 ; } } } cout << answer ; } int main ( ) { int arr [ ] = { 2 , 3 , 9 , 5 , 4 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumSubarrays ( arr , n ) ; return 0 ; }