[LeetCode] Find All Good Indices

2420. Find All Good Indices

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 index i are in non-increasing order.
  • The k elements that are just after the index i are in non-decreasing order.

Return an array of all good indices sorted in increasing order.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> goodIndices(vector<int>& A, int k) {
int n = A.size();
vector<int> inc(n,1), dec(n,1);
for(int i = 1; i < n; i++) if(A[i-1] >= A[i]) dec[i] = dec[i-1] + 1;
for(int i = n - 2; i >= 0; i--) if(A[i+1] >= A[i]) inc[i] = inc[i+1] + 1;
vector<int> res;
for(int i = k; i < n - k; i++) if(inc[i+1] >= k and dec[i-1] >= k) res.push_back(i);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/10/PS/LeetCode/find-all-good-indices/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.