题目:
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security
, where security[i]
is the number of guards on duty on the ith
day. The days are numbered starting from 0
. You are also given an integer time
.
The ith
day is a good day to rob the bank if:
- There are at least
time
days before and after theith
day, - The number of guards at the bank for the
time
days beforei
are non-increasing, and - The number of guards at the bank for the
time
days afteri
are non-decreasing.
More formally, this means day i
is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]
.
Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.
Example 1:
Input: security = [5,3,3,3,5,6,2], time = 2 Output: [2,3] Explanation: On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4]. On day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5]. No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.
Example 2:
Input: security = [1,1,1,1,1], time = 0 Output: [0,1,2,3,4] Explanation: Since time equals 0, every day is a good day to rob the bank, so return every day.
Example 3:
Input: security = [1,2,3,4,5,6], time = 2 Output: [] Explanation: No day has 2 days before it that have a non-increasing number of guards. Thus, no day is a good day to rob the bank, so return an empty list.
Constraints:
1 <= security.length <= 105
0 <= security[i], time <= 105
思路:
本题是个小dp题,只要知道每个i前面最长非递增长度和后面每个非递减长度即可,之后再和time逐一比较获得答案。因为左右对称,可以用一次遍历来获得dp数值。对于before,只要security[i]不比前一个小,before[i]等于before[i - 1] + 1,这里before[i]代表的就是i前面最长的非递增长度。反之同样的处理after,只要注意相对的index即可。顺便吐槽这个题目,打劫银行可还行,不愧自由美利坚,BOA,chase瑟瑟发抖。
代码:
class Solution {
public:
vector<int> goodDaysToRobBank(vector<int>& security, int time) {
int n = security.size();
vector<int> before(n), after(n);
for (int i = 1; i < n; i++) {
if (security[i] <= security[i - 1])
before[i] = before[i - 1] + 1;
if (security[n - i - 1] <= security[n - i])
after[n - i - 1] = after[n - i] + 1;
}
vector<int> res;
for (int i = time; i < n - time; i++) {
if (before[i] >= time && after[i] >= time)
res.push_back(i);
}
return res;
}
};