Problem Description
Given an array of integers representing the number of guards on duty each day, find all the days (0-indexed) that are good for robbing the bank. A day is considered good if there are at least “time” days before and after it, such that the previous “time” days are in non-increasing order and the following “time” days are in non-decreasing order.
Key Insights
- If time is 0, every day is a good day.
- Use two passes (one forward and one backward) to precompute how many consecutive days (including the current day) fulfill the non-increasing and non-decreasing conditions.
- For the left side, count consecutive days where the guard number does not increase.
- For the right side, count consecutive days where the guard number does not decrease.
- A valid day must have at least “time” consecutive days on both sides.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the security array. Space Complexity: O(n), for the two auxiliary arrays used during the passes.
Solution
We will use a dynamic programming approach by computing two arrays:
- left[]: For each day, it stores the number of consecutive previous days (up to the current day) that form a non-increasing sequence.
- right[]: For each day, it stores the number of consecutive following days (starting at the current day) that form a non-decreasing sequence.
For each day i (excluding the first and last “time” days), check if left[i] >= time and right[i] >= time. If so, add i to the result list.
The key trick here is to count the sequences in one pass to avoid rechecking each window, which keeps the solution efficient.