Skip to content

Commit 9d06c06

Browse files
authored
Create smallest-subarray-to-sort-in-every-sliding-window.cpp
1 parent 646a7ef commit 9d06c06

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// mono stack, two pointers
5+
class Solution {
6+
public:
7+
vector<int> minSubarraySort(vector<int>& nums, int k) {
8+
const int n = size(nums);
9+
const auto& count = [&](const auto& nums) {
10+
vector<int> nxt(n, n), stk;
11+
for (int i = n - 1; i >= 0; --i) {
12+
while (!(empty(stk) || nums[stk.back()] >= nums[i])) {
13+
stk.pop_back();
14+
}
15+
if (!empty(stk)) {
16+
nxt[i] = stk.back();
17+
}
18+
stk.emplace_back(i);
19+
}
20+
vector<int> result;
21+
for (int i = 1, j = 0, left = -1; i < n; ++i) {
22+
if (nums[i] < nums[i - 1]) {
23+
left = i;
24+
}
25+
if (i < k - 1) {
26+
continue;
27+
}
28+
j = max(j, i - (k - 1));
29+
while (!(nxt[j] > left)) {
30+
j = nxt[j]; // or j += 1
31+
}
32+
result.emplace_back(max(i - nxt[j] + 1, 0));
33+
}
34+
return result;
35+
};
36+
37+
vector<int> result(n - k + 1);
38+
if (k == 1) {
39+
return result;
40+
}
41+
const auto& right = count(nums);
42+
for (int i = 0; i <= n - 1 - i; ++i) {
43+
tie(nums[i], nums[n - 1 - i]) = pair(-nums[n - 1 - i], -nums[i]);
44+
}
45+
const auto& left = count(nums);
46+
for (int i = 0; i < size(result); ++i) {
47+
result[i] = max(k - left[((n - k + 1) - 1) - i] - right[i], 0);
48+
}
49+
return result;
50+
}
51+
};

0 commit comments

Comments
 (0)