Skip to content

2420. Find All Good Indices 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  // Same as 2100. Find Good Days to Rob the Bank
  vector<int> goodIndices(vector<int>& nums, int k) {
    const int n = nums.size();
    vector<int> ans;
    // dec[i] := 1 + the number of continuous decreasing numbers before i
    vector<int> dec(n, 1);
    // inc[i] := 1 + the number of continuous increasing numbers after i
    vector<int> inc(n, 1);

    for (int i = 1; i < n; ++i)
      if (nums[i - 1] >= nums[i])
        dec[i] = dec[i - 1] + 1;

    for (int i = n - 2; i >= 0; --i)
      if (nums[i] <= nums[i + 1])
        inc[i] = inc[i + 1] + 1;

    for (int i = k; i < n - k; ++i)
      if (dec[i - 1] >= k && inc[i + 1] >= k)
        ans.push_back(i);

    return ans;
  }
};
 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
class Solution {
  // Same as 2100. Find Good Days to Rob the Bank
  public List<Integer> goodIndices(int[] nums, int k) {
    final int n = nums.length;
    List<Integer> ans = new ArrayList<>();
    // dec[i] := 1 + the number of continuous decreasing numbers before i
    int[] dec = new int[n];
    // inc[i] := 1 + the number of continuous increasing numbers after i
    int[] inc = new int[n];

    Arrays.fill(dec, 1);
    Arrays.fill(inc, 1);

    for (int i = 1; i < n; ++i)
      if (nums[i - 1] >= nums[i])
        dec[i] = dec[i - 1] + 1;

    for (int i = n - 2; i >= 0; --i)
      if (nums[i] <= nums[i + 1])
        inc[i] = inc[i + 1] + 1;

    for (int i = k; i < n - k; ++i)
      if (dec[i - 1] >= k && inc[i + 1] >= k)
        ans.add(i);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  # Same as 2100. Find Good Days to Rob the Bank
  def goodIndices(self, nums: list[int], k: int) -> list[int]:
    n = len(nums)
    dec = [1] * n  # 1 + the number of continuous decreasing numbers before i
    inc = [1] * n  # 1 + the number of continuous increasing numbers after i

    for i in range(1, n):
      if nums[i - 1] >= nums[i]:
        dec[i] = dec[i - 1] + 1

    for i in range(n - 2, -1, -1):
      if nums[i] <= nums[i + 1]:
        inc[i] = inc[i + 1] + 1

    return [i for i in range(k, n - k)
            if dec[i - 1] >= k and inc[i + 1] >= k]