PREFIX SUM › PREFIX SUM
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A day i is valid only when two independent conditions meet at the same index. Looking left from i, guard counts must never increase as you approach i. Looking right from i, guard counts must never decrease as you move away from i. The day also needs time positions on each side, so the two conditions can only matter for indices from time through n - time - 1.
For every index, store how many consecutive comparisons succeed on its left and how many succeed on its right. The left count grows when security[i] <= security[i - 1]; otherwise the non-increasing run stops. The right count grows when security[i] <= security[i + 1], computed from right to left. A day is good exactly when both stored counts are at least time.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The left pass, right pass, and final scan each inspect every index at most once. Their costs add to three linear scans, so no index causes repeated expansion of a run. |
| Space | O(n) extra | The left and right arrays each contain n counts, and the answer is required output rather than working memory. The extra space remains O(n) for every input shape because the two arrays are allocated by length, even when every comparison fails. |
#include <vector>
using namespace std;
class Solution {
public:
vector<int> goodDaysToRobBank(vector<int>& security, int time) {
int n = security.size();
vector<int> left(n, 0), right(n, 0);
for (int i = 1; i < n; ++i) {
if (security[i] <= security[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; --i) {
if (security[i] <= security[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
vector<int> ans;
for (int i = time; i < n - time; ++i) {
if (left[i] >= time && right[i] >= time) {
ans.push_back(i);
}
}
return ans;
}
};The initialization to zero is doing more than setting defaults. At index i, left[i] counts comparisons ending at i, so the first possible comparison begins at index 1. Similarly, right[i] counts comparisons beginning at i, so the last possible comparison is at index n - 2. The final loop's bounds handle the separate requirement that enough actual days exist on both sides.