# Max Chunks To Make Sorted II in C++

C++Server Side ProgrammingProgramming

Suppose we have an array arr of integers, we have to split the array into some number of partitions, and individually sort each partition. Now after concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made?

So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], , , .

To solve this, we will follow these steps −

• cnt := 1

• n := size of arr

• Define an array maxOfLeft of size n

• Define an array minOfRight of size n

• maxOfLeft := arr

• for initialize i := 1, when i < n, update (increase i by 1), do −

• maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]

• minOfRight[n - 1] = arr[n - 1]

• for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −

• minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]

• for initialize i := 0, when i < n - 1, update (increase i by 1), do −

• if minOfRight[i + 1] >= maxOfLeft[i], then −

• (increase cnt by 1)

• return cnt

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int cnt = 1;
int n = arr.size();
vector<int> maxOfLeft(n);
vector<int> minOfRight(n);
maxOfLeft = arr;
for (int i = 1; i < n; i++)
maxOfLeft[i] = max(maxOfLeft[i - 1], arr[i]);
minOfRight[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
minOfRight[i] = min(minOfRight[i + 1], arr[i]);
for (int i = 0; i < n - 1; i++) {
if (minOfRight[i + 1] >= maxOfLeft[i])
cnt++;
}
return cnt;
}
};
main(){
Solution ob;
vector<int> v = {3,2,4,5,5};
cout << (ob.maxChunksToSorted(v));
}

## Input

{3,2,4,5,5}

## Output

4