Skip to content

Commit 622fad6

Browse files
committed
Runtime: 3 ms (Top 97.81%) | Memory: 12.70 MB (Top 49.02%)
1 parent f079ae0 commit 622fad6

File tree

1 file changed

+16
-44
lines changed

1 file changed

+16
-44
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,20 @@
1-
class BIT {
2-
public:
3-
BIT(int capacity) : nodes(capacity + 1, 0) {}
4-
BIT(const vector<int>& nums) : nodes(nums.size() + 1, 0) {
5-
for (int i = 0; i < nums.size(); ++i) {
6-
update(i + 1, nums[i]);
7-
}
8-
}
9-
10-
void update(int idx, int val) {
11-
for (int i = idx; i < nodes.size(); i += i & -i) {
12-
nodes[i] += val;
13-
}
14-
}
15-
16-
int query(int idx) {
17-
int ans = 0;
18-
for (int i = idx; i > 0; i -= i & -i) {
19-
ans += nodes[i];
20-
}
21-
return ans;
22-
}
23-
24-
private:
25-
vector<int> nodes;
26-
};
1+
// Runtime: 3 ms (Top 97.81%) | Memory: 12.70 MB (Top 49.02%)
272

283
class Solution {
29-
public:
30-
int maxChunksToSorted(vector<int>& arr) {
31-
int n = arr.size();
32-
BIT bit(n);
33-
unordered_map<int, int> h;
34-
vector<int> sorted = arr;
35-
sort(sorted.begin(), sorted.end());
36-
for (int i = 0; i < n; ++i) {
37-
if (i == 0 || sorted[i - 1] != sorted[i]) h[sorted[i]] = i + 1;
38-
}
39-
40-
int ans = 0;
41-
for (int i = 0; i < n; ++i) {
42-
bit.update(h[arr[i]], 1);
43-
++h[arr[i]];
44-
if (bit.query(i + 1) == i + 1) ans += 1;
4+
public:
5+
int maxChunksToSorted(vector<int>& arr) {
6+
vector<int>right(arr.size()+1);
7+
right[arr.size()] = INT_MAX;
8+
9+
for(int i =arr.size()-1 ; i>= 0; i--){
10+
right[i] = min(right[i+1], arr[i]);
11+
}
12+
int left_max = INT_MIN;
13+
int count_chunks =0;
14+
for(int i =0; i<arr.size(); i++){
15+
left_max = max(left_max, arr[i]);
16+
if(left_max <= right[i+1]) count_chunks++;
17+
}
18+
return count_chunks;
4519
}
46-
return ans;
47-
}
4820
};

0 commit comments

Comments
 (0)