forked from ligua/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax-chunks-to-make-sorted-ii.cpp
39 lines (36 loc) · 1.06 KB
/
max-chunks-to-make-sorted-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Time: O(n)
// Space: O(n)
// mono stack solution
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
vector<int> increasing_stk;
for (const auto& num : arr) {
int max_num = empty(increasing_stk) ? num : max(increasing_stk.back(), num);
while (!empty(increasing_stk) && increasing_stk.back() > num) {
increasing_stk.pop_back();
}
increasing_stk.emplace_back(max_num);
}
return size(increasing_stk);
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
int maxChunksToSorted(vector<int>& arr) {
vector<int> idxs(arr.size());
iota(idxs.begin(), idxs.end(), 0);
sort(idxs.begin(), idxs.end(),
[&](int i1, int i2) {
return arr[i1] != arr[i2] ? arr[i1] < arr[i2] : i1 < i2;
});
int result = 0;
for (auto i = 0, max_i = 0; i < idxs.size(); ++i) {
max_i = max(max_i, idxs[i]);
if (max_i == i) ++result;
}
return result;
}
};