[LeetCode] Max Chunks To Make Sorted II

768. Max Chunks To Make Sorted II

You are given an integer array arr.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
unordered_map<int, int> counter;
vector<int> sorted = arr;
sort(sorted.begin(), sorted.end());
int res = 0, n = arr.size();

for(int i = 0; i < n; i++) {
if(++counter[arr[i]] == 0)
counter.erase(arr[i]);
if(--counter[sorted[i]] == 0)
counter.erase(sorted[i]);

if(counter.empty())
res++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/max-chunks-to-make-sorted-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.