#2100

Find Good Days to Rob the Bank

Medium
ArrayDynamic ProgrammingPrefix SumArrayDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution precomputes the number of consecutive non-increasing days before each day and non-decreasing days after each day. This allows us to determine if a day is good in constant time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two arrays, 'left' and 'right', to store the counts of non-increasing and non-decreasing days.
  2. 2Step 2: Fill the 'left' array by iterating through the security array to count consecutive non-increasing days.
  3. 3Step 3: Fill the 'right' array similarly for non-decreasing days.
  4. 4Step 4: Iterate through each day and check if both 'left[i] >= time' and 'right[i] >= time' to determine good days.
solution.py11 lines
1def goodDaysToRobBank(security, time):
2    n = len(security)
3    left = [0] * n
4    right = [0] * n
5    for i in range(1, n):
6        if security[i] <= security[i - 1]:
7            left[i] = left[i - 1] + 1
8    for i in range(n - 2, -1, -1):
9        if security[i] <= security[i + 1]:
10            right[i] = right[i + 1] + 1
11    return [i for i in range(time, n - time) if left[i] >= time and right[i] >= time]

Complexity note: The complexity is linear because we traverse the security array a constant number of times (twice) to build the left and right arrays.

  • 1Precomputation can significantly reduce repeated calculations.
  • 2Understanding the conditions for good days helps in optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.