Skip to content

2100. Find Good Days to Rob the Bank 👍

  • 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
class Solution {
 public:
  vector<int> goodDaysToRobBank(vector<int>& security, int time) {
    const int n = security.size();
    vector<int> ans;
    // dec[i] := the number of continuous decreasing numbers before i
    vector<int> dec(n);
    // inc[i] := the number of continuous increasing numbers after i
    vector<int> inc(n);

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

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

    for (int i = 0; i < n; ++i)
      if (dec[i] >= time && inc[i] >= time)
        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
class Solution {
  public List<Integer> goodDaysToRobBank(int[] security, int time) {
    final int n = security.length;
    List<Integer> ans = new ArrayList<>();
    // dec[i] := the number of continuous decreasing numbers before i
    int[] dec = new int[n];
    // inc[i] := the number of continuous increasing numbers after i
    int[] inc = new int[n];

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

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

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

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def goodDaysToRobBank(self, security: list[int], time: int) -> list[int]:
    n = len(security)
    dec = [0] * n  # dec[i] := the number of continuous decreasing numbers before i
    inc = [0] * n  # inc[i] := the number of continuous increasing numbers after i

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

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

    return [i for i, (a, b) in enumerate(zip(dec, inc))
            if a >= time and b >= time]