Maximum number of partitions that can be sorted individually to make sorted in C++

C++Server Side ProgrammingProgramming

We are given with an array of N numbers with elements lying in range 0 and N-1. The elements are unsorted. The goal is to find the maximum number of partitions of the array which can be sorted individually and then can be concatenated to make a whole sorted array of length N.

Each partition is chosen such that elements in it are unsorted. For N numbers ranging between 0 and N-1, sorted elements are at index equal to the value. Arr[i] = i.

We will solve this by comparing each element by maximum value found so far on its left. When reached at the correct position of maximum, (maximum == i ). All elements to its left are less so can make a separate partition. All to its right are greater. Now do the same procedure for the rest of the right elements and divide them into partitions.

Let’s understand with examples.

Input − Arr[]={ 0,3,2,1,4,5 }

Output − Maximum number of partitions − 3

Explanation − Starting from 0, Let max=0 Arr[0]

Between index 0 and 3. 3 is maximum. When reached at index i=3 ( maxx==i). So first partition is [0,3,2,1]

For index 4, maximum is 4. Index i=4 ( maxx==i). So second partition is [4]

For index 5, maximum is 5. Index i=5 ( maxx==i). So second partition is [5]

Total 3 partitions [0,3,2,1][4][5]. Sort each and concatenate.

Input − Arr[]={ 5,4,3,2,1,0 }

Output − Maximum number of partitions − 1

Explanation − Starting from 0, Let max=0 Arr[0]

Between index 0 and 5. 5 is maximum. When reached at index i=5 ( maxx==i). So only partition is [5,4,3,2,1,0]

Approach used in the below program is as follows

  • We take an integer array Num[] initialized with numbers in range 0 to N.

  • Function partitions(int arr[], int n ) takes an array and its length as parameters and returns the count of maximum partitions that can be individually sorted to make the whole array sorted.

  • Initial partition count is 0. Initial maximum value is in maxx as arr[0].

  • For all elements starting from the leftmost element. Find if it's greater than maxx.

  • If arr[i]>maxx is true. Update maxx.

  • If the current maxx and index is the same. ( maxx==i ) then all elements upto i are part of one partition. Increment count.

  • Do this for the rest of the elements on the right till end.

  • Return the result as count.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int partitions(int arr[], int n){
   int count = 0;
   int maxx = arr[0];
   for (int i = 0; i < n; ++i) {
      if(arr[i] > maxx)
         maxx=arr[i];
      if (maxx == i)
         count++;
   }
   return count;
}
int main(){
   int Num[] = { 2,1,0,4,5,3 };
   int len = 6;
   cout <<"Maximum partitions that can be sorted: "<<partitions(Num, len);
   return 0;
}

Output

If we run the above code it will generate the following output −

Maximum partitions that can be sorted: 18
raja
Published on 29-Aug-2020 08:25:13
Advertisements