- tags: Tricky,LeetCode101
original: 0, 2, 1, 4, 3, 5, 7, 6 max: 0, 2, 2, 4, 4, 5, 7, 7 sorted: 0, 1, 2, 3, 4, 5, 6, 7 index: 0, 1, 2, 3, 4, 5, 6, 7
As shown above, the position of break point is same to the position of max
value of chunks.
So here:
- We track chunks’s
max
value. - Break at the position of
max
value lives in sorted array, which means the index in this case.
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int count = 0, m = 0;
for (int i = 0; i < arr.size(); i++) {
m = max(arr[i], m);
if (m == i) {
count++;
}
}
return count;
}
};