Untitled
unknown
plain_text
a year ago
1.8 kB
10
Indexable
class Solution {
public List<Integer> goodDaysToRobBank(int[] security, int time) {
// Get the length of the `security` array.
int n = security.length;
// If the length is not sufficient to have days before and after the time period, return an empty list.
if (n <= time * 2) {
return Collections.emptyList();
}
// Arrays to keep track of the non-increasing trend to the left and non-decreasing trend to the right.
int[] nonIncreasingLeft = new int[n];
int[] nonDecreasingRight = new int[n];
// Populate the nonIncreasingLeft array by checking if each day is non-increasing compared to the previous day.
for (int i = 1; i < n; ++i) {
if (security[i] <= security[i - 1]) {
nonIncreasingLeft[i] = nonIncreasingLeft[i - 1] + 1;
}
}
// Populate the nonDecreasingRight array by checking if each day is non-decreasing compared to the next day.
for (int i = n - 2; i >= 0; --i) {
if (security[i] <= security[i + 1]) {
nonDecreasingRight[i] = nonDecreasingRight[i + 1] + 1;
}
}
// To store the good days to rob the bank.
List<Integer> goodDays = new ArrayList<>();
// Check each day to see if it can be a good day to rob the bank.
for (int i = time; i < n - time; ++i) {
// A day is good if there are at least `time` days before and after it forming non-increasing and non-decreasing trends.
if (time <= Math.min(nonIncreasingLeft[i], nonDecreasingRight[i])) {
goodDays.add(i);
}
}
// Return the list of good days.
return goodDays;
}
}Editor is loading...
Leave a Comment