Given an array arr[] of size N, the task is to split the given array into a minimum number of subarrays such that elements of each subarray are either in non-increasing order or non-decreasing order.
Examples:
Input: arr[] = {2, 3, 9, 5, 4, 6, 8}
Output: 3
Explanation: Split the array into 3 subarrays following three subarrays:Â
- {2, 3, 9} (non-decreasing)
- {5, 4} (non-increasing)
- {6, 8} (non-decreasing)
Input: arr[] = {2, 5, 3, 3, 4, 5, 0, 2, 1, 0}Â
Output: 4
Explanation: Split the array into following 4 subarray:Â
- {2, 5} (non-decreasing)
- {3, 3, 4, 5} (non-decreasing)
- {0, 2} (non-decreasing)
- {1, 0} (non-increasing)
Approach: To minimize the number of subarrays, the size of each subarray should be maximized. It can be done by placing the elements in subarrays greedily.Â
Follow the steps below to solve the problem:
- Initialize a variable, say ans, with 1 to store the required result and current with N to keep track of the order of the current sequence, whether it is non-decreasing(I), non-increasing(D), or none(N).
- Now, iterate over the array in the range [1, N – 1]:
- If the current is equal to N, do the following:Â
- If arr[i] < arr[i-1] then update current as D.
- Otherwise, if arr[i] > arr[i-1], then update current as I.
- Otherwise, update current as N.
- If the current is equal to I, do the following:
- If arr[i]?arr[i-1] then update current as I.
- Otherwise, update current as N and increment ans by 1.
- Otherwise, do the following:
- If arr[i] ? arr[i-1], then update current as D.
- Otherwise, update current as N and increment ans by 1.
- If the current is equal to N, do the following:Â
- After the above steps, print the value of ans as the result.
Below is the implementation of the above approach:Â
C++
#include <bits/stdc++.h> using namespace std; Â
// Function to split the array into minimum count // of subarrays such that each subarray is either // non-increasing or non-decreasing void minimumSubarrays( int arr[], int n) { Â
  // Initialize variable to keep   // track of current sequence   char current = 'N' ; Â
  // Stores the required result   int answer = 1; Â
  // Traverse the array, arr[]   for ( int i = 1; i < n; i++) { Â
    // If current sequence is neither     // non-increasing nor non-decreasing     if (current == 'N' ) { Â
      // If previous element is greater       if (arr[i] < arr[i - 1]) { Â
        // Update current         current = 'D' ;       } Â
      // If previous element is equal       // to the current element       else if (arr[i] == arr[i - 1]) { Â
        // Update current         current = 'N' ;       } Â
      // Otherwise       else { Â
        // Update current         current = 'I' ;       }     } Â
    // If current sequence     // is in non-decreasing     else if (current == 'I' ) { Â
      // If previous element is       // less than or equal to       // the current element       if (arr[i] >= arr[i - 1]) {         current = 'I' ;       } Â
      // Otherwise       else { Â
        // Update current as N and         // increment answer by 1         current = 'N' ;         answer += 1;       }     } Â
    // If current sequence     // is Non-Increasing     else { Â
      // If previous element is       // greater or equal to       // the current element       if (arr[i] <= arr[i - 1]) {         current = 'D' ;       } Â
      // Otherwise       else { Â
        // Update current as N and         // increment answer by 1         current = 'N' ;         answer += 1;       }     }   } Â
  // Print the answer   cout<<answer; } Â
// Driver Code int main() { Â
  // Given array   int arr[] = { 2, 3, 9, 5, 4, 6, 8 }; Â
  // Given size of array   int n = sizeof (arr) / sizeof (arr[0]); Â
  minimumSubarrays(arr, n);   return 0; } Â
// This code is contributed by shikhasingrajput |
Java
// Java program for the above approach Â
import java.io.*; import java.util.*; Â
class GFG { Â
    // Function to split the array into minimum count     // of subarrays such that each subarray is either     // non-increasing or non-decreasing     static void minimumSubarrays( int [] arr, int n)     { Â
        // Initialize variable to keep         // track of current sequence         char current = 'N' ; Â
        // Stores the required result         int answer = 1 ; Â
        // Traverse the array, arr[]         for ( int i = 1 ; i < n; i++) { Â
            // If current sequence is neither             // non-increasing nor non-decreasing             if (current == 'N' ) { Â
                // If previous element is greater                 if (arr[i] < arr[i - 1 ]) { Â
                    // Update current                     current = 'D' ;                 } Â
                // If previous element is equal                 // to the current element                 else if (arr[i] == arr[i - 1 ]) { Â
                    // Update current                     current = 'N' ;                 } Â
                // Otherwise                 else { Â
                    // Update current                     current = 'I' ;                 }             } Â
            // If current sequence             // is in non-decreasing             else if (current == 'I' ) { Â
                // If previous element is                 // less than or equal to                 // the current element                 if (arr[i] >= arr[i - 1 ]) {                     current = 'I' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1 ;                 }             } Â
            // If current sequence             // is Non-Increasing             else { Â
                // If previous element is                 // greater or equal to                 // the current element                 if (arr[i] <= arr[i - 1 ]) {                     current = 'D' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1 ;                 }             }         } Â
        // Print the answer         System.out.print(answer);     } Â
    // Driver Code     public static void main(String[] args)     { Â
        // Given array         int arr[] = { 2 , 3 , 9 , 5 , 4 , 6 , 8 }; Â
        // Given size of array         int n = arr.length; Â
        minimumSubarrays(arr, n);     } } |
Python3
# Python3 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 def minimumSubarrays(arr, n): Â
    # Initialize variable to keep     # track of current sequence     current = 'N' Â
    # Stores the required result     answer = 1 Â
    # Traverse the array, arr[]     for i in range ( 1 , n): Â
        # If current sequence is neither         # non-increasing nor non-decreasing         if (current = = 'N' ): Â
            # If previous element is greater             if (arr[i] < arr[i - 1 ]): Â
                # Update current                 current = 'D' Â
            # If previous element is equal             # to the current element             elif (arr[i] = = arr[i - 1 ]): Â
                # Update current                 current = 'N' Â
            # Otherwise             else : Â
                # Update current                 current = 'I' Â
        # If current sequence         # is in non-decreasing         elif (current = = 'I' ): Â
            #I f previous element is             # less than or equal to             # the current element             if (arr[i] > = arr[i - 1 ]):                 current = 'I' Â
            # Otherwise             else : Â
                # Update current as N and                 # increment answer by 1                 current = 'N'                 answer + = 1 Â
        # If current sequence         # is Non-Increasing         else : Â
            # If previous element is             # greater or equal to             # the current element             if (arr[i] < = arr[i - 1 ]):                 current = 'D' Â
            # Otherwise             else : Â
                # Update current as N and                 # increment answer by 1                 current = 'N'                 answer + = 1 Â
    # Print the answer     print (answer) Â
# Driver Code if __name__ = = '__main__' : Â
    # Given array     arr = [ 2 , 3 , 9 , 5 , 4 , 6 , 8 ] Â
    # Given size of array     n = len (arr)          minimumSubarrays(arr, n) Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG { Â
    // Function to split the array into minimum count     // of subarrays such that each subarray is either     // non-increasing or non-decreasing     static void minimumSubarrays( int [] arr, int n)     { Â
        // Initialize variable to keep         // track of current sequence         char current = 'N' ; Â
        // Stores the required result         int answer = 1; Â
        // Traverse the array, []arr         for ( int i = 1; i < n; i++) { Â
            // If current sequence is neither             // non-increasing nor non-decreasing             if (current == 'N' ) { Â
                // If previous element is greater                 if (arr[i] < arr[i - 1]) { Â
                    // Update current                     current = 'D' ;                 } Â
                // If previous element is equal                 // to the current element                 else if (arr[i] == arr[i - 1]) { Â
                    // Update current                     current = 'N' ;                 } Â
                // Otherwise                 else { Â
                    // Update current                     current = 'I' ;                 }             } Â
            // If current sequence             // is in non-decreasing             else if (current == 'I' ) { Â
                // If previous element is                 // less than or equal to                 // the current element                 if (arr[i] >= arr[i - 1]) {                     current = 'I' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1;                 }             } Â
            // If current sequence             // is Non-Increasing             else { Â
                // If previous element is                 // greater or equal to                 // the current element                 if (arr[i] <= arr[i - 1]) {                     current = 'D' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1;                 }             }         } Â
        // Print the answer         Console.Write(answer);     } Â
    // Driver Code     public static void Main(String[] args)     { Â
        // Given array         int []arr = { 2, 3, 9, 5, 4, 6, 8 }; Â
        // Given size of array         int n = arr.Length; Â
        minimumSubarrays(arr, n);     } } Â
// This code is contributed by 29AjayKumar |
Javascript
<script> // Java script 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     function minimumSubarrays(arr,n)     { Â
        // Initialize variable to keep         // track of current sequence         let current = 'N' ; Â
        // Stores the required result         let answer = 1; Â
        // Traverse the array, arr[]         for (let i = 1; i < n; i++) { Â
            // If current sequence is neither             // non-increasing nor non-decreasing             if (current == 'N' ) { Â
                // If previous element is greater                 if (arr[i] < arr[i - 1]) { Â
                    // Update current                     current = 'D' ;                 } Â
                // If previous element is equal                 // to the current element                 else if (arr[i] == arr[i - 1]) { Â
                    // Update current                     current = 'N' ;                 } Â
                // Otherwise                 else { Â
                    // Update current                     current = 'I' ;                 }             } Â
            // If current sequence             // is in non-decreasing             else if (current == 'I' ) { Â
                // If previous element is                 // less than or equal to                 // the current element                 if (arr[i] >= arr[i - 1]) {                     current = 'I' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1;                 }             } Â
            // If current sequence             // is Non-Increasing             else { Â
                // If previous element is                 // greater or equal to                 // the current element                 if (arr[i] <= arr[i - 1]) {                     current = 'D' ;                 } Â
                // Otherwise                 else { Â
                    // Update current as N and                     // increment answer by 1                     current = 'N' ;                     answer += 1;                 }             }         } Â
        // Print the answer         document.write(answer);     } Â
    // Driver Code              // Given array         let arr = [ 2, 3, 9, 5, 4, 6, 8 ]; Â
        // Given size of array         let n = arr.length; Â
        minimumSubarrays(arr, n); Â
// contributed by sravan kumar </script> |
3
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!