Posted on

 Max Chunks To Make Sorted

You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].

We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return the largest number of chunks we can make to sort the array.

Example 1:

Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.

Example 2:

Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.

Solution

The core idea behind the solution is to identify contiguous subsequences within the array A where the elements form a consecutive sequence starting from 0.

We iterate through the array, keeping track of the current chunk’s starting index. As long as the current element matches its index, we continue iterating. Once we encounter an element that doesn’t match its index, we’ve reached the end of the current chunk. We then append this chunk to a list of chunks and start the process again from the next element.

//
// Created by robert on 12/18/24.
//
#include <vector>
#include <iostream>

using namespace std;

int maxChunksToSorted(const vector<int>& arr) {
int chunks = 0, i =0;;

while(i < arr.size()){
int start = i;
int max_val = arr[start];
while( i < arr.size() && max_val >= i ){
max_val = max(max_val, arr[i]);
++i;
}
++chunks;
}

return chunks;
}

vector<vector<int>> findChunks(const vector<int>& arr) {
int i =0;
vector<vector<int>> chunks;
while(i < arr.size()){
int start = i;
int max_val = arr[start];
while( i < arr.size() && max_val >= i ){
max_val = max(max_val, arr[i]);
++i;
}
chunks.emplace_back(vector<int>(arr.begin() + start, arr.begin() + i));
}

return chunks;
}

void printChunks(const vector<int>& arr) {
vector<vector<int> > chunks = findChunks(arr);
cout << "[";
for (size_t i = 0; i < chunks.size(); ++i) {
cout << "[";
for (size_t j = 0; j < chunks[i].size(); ++j) {
cout << chunks[i][j];
if (j != chunks[i].size() - 1) cout << ",";
}
cout << "]";
if (i != chunks.size() - 1) cout << ",";
}
cout << "]" << endl;

}

int main(int argc, char *argv[]) {
cout << maxChunksToSorted({4,3,2,1,0}) << endl;
cout << maxChunksToSorted({1,0,2,3,4}) << endl;
cout << maxChunksToSorted({1,0, 2,3,4,5}) << endl;

printChunks({1, 0, 2, 3, 4});
printChunks({4, 3, 1, 2, 0});
printChunks({1, 0, 3, 2, 4});
printChunks({ 1, 2, 3, 4, 5, 0});
printChunks({0, 1, 2, 3, 10, 11, 12});
return 0;
}

/home/robert/CLionProjects/untitled/maxChunksToSorted
1
4
5
[[1,0],[2],[3],[4]]
[[4,3,1,2,0]]
[[1,0],[3,2],[4]]
[[1,2,3,4,5,0]]
[[0],[1],[2],[3],[10,11,12]]

Process finished with exit code 0