769. Max Chunks To Make Sorted
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.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.// Two Pass with O(n) Space Usage
int maxChunksToSorted(vector<int>& arr) { // time: O(n); space: O(n)
if (arr.empty()) return 0;
int n = arr.size(), res = 0;
vector<int> largest(n, 0);
largest[0] = arr[0];
for (int i = 1; i < n; ++i) {
largest[i] = max(largest[i - 1], arr[i]);
}
for (int i = 0; i < n; ++i) {
if (largest[i] == i) ++res;
}
return res;
}Last updated