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

    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
class Solution {
  public List<Integer> goodDaysToRobBank(int[] security, int time) {
    final int n = security.length;
    List<Integer> ans = new ArrayList<>();
    int[] dec = new int[n]; // dec[i] := continuous decreasings before i
    int[] inc = new int[n]; // inc[i] := continuous increasings after i

    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] := continuous decreasings before i
    inc = [0] * n  # inc[i] := continuous increasings 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]