You are given a 0-indexed integer array nums
of size n
and a positive integer k
.
We call an index i
in the range k <= i < n - k
good if the following conditions are satisfied:
- The
k
elements that are just before the indexi
are in non-increasing order. - The
k
elements that are just after the indexi
are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.
Constraints:
n == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2
Companies: Goldman Sachs
Related Topics:
Array, Dynamic Programming, Prefix Sum
Similar Questions:
- Find Good Days to Rob the Bank (Medium)
- Abbreviating the Product of a Range (Hard)
- Count the Number of K-Big Indices (Hard)
// OJ: https://leetcode.com/problems/find-all-good-indices
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(K)
class Solution {
public:
vector<int> goodIndices(vector<int>& A, int k) {
vector<int> ans;
deque<int> left, right;
for (int i = 0, N = A.size(); i < N; ++i) {
if (i - k - 1 >= 0) {
while (left.size() && A[left.back()] < A[i - k - 1]) left.pop_back();
left.push_back(i - k - 1);
}
if (left.size() && left.front() < i - 2 * k) left.pop_front();
while (right.size() && A[right.back()] > A[i]) right.pop_back();
right.push_back(i);
if (right.front() == i - k) right.pop_front();
if (left.size() == k && right.size() == k) ans.push_back(i - k);
}
return ans;
}
};
// OJ: https://leetcode.com/problems/find-all-good-indices
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> goodIndices(vector<int>& A, int k) {
int N = A.size();
vector<int> ans, left(N, 1), right(N, 1);
for (int i = 1; i < N; ++i) {
if (A[i] <= A[i - 1]) left[i] = left[i - 1] + 1;
}
for (int i = N - 2; i >= 0; --i) {
if (A[i] <= A[i + 1]) right[i] = right[i + 1] + 1;
}
for (int i = k; i < N - k; ++i) {
if (left[i - 1] >= k && right[i + 1] >= k) ans.push_back(i);
}
return ans;
}
};