2024-12-19 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp
.
December LeetCoding Challenge 19
Description
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.
Constraints:
n == arr.length
1 <= n <= 10
0 <= arr[i] < n
- All the elements of
arr
are unique.
Solution
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
vector<int> newArr(arr.begin(), arr.end());
sort(newArr.begin(), newArr.end());
map<int, set<int>> positions;
for(int i = 0; i < arr.size(); ++i) {
positions[newArr[i]].insert(i);
}
int answer = 0;
int end = -1;
for(int i = 0; i < arr.size(); ++i) {
int pos = *positions[arr[i]].begin();
positions[arr[i]].erase(pos);
end = max(end, pos);
if(end == i) {
answer += 1;
end = -1;
}
}
return answer;
}
};
// Accepted
// 52/52 cases passed (3 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 20.72 % of cpp submissions (9.3 MB)