Longest Well-Performing Interval
We are given hours
, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8
.
A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.
Return the length of the longest well-performing interval.
Example 1:
Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].
Thoughts
一串数字,找其中满足值大于8元素个数大于不满足的个数的最长子数组。
元素分成两种,并且要比较两种的个数,想到可以+1-1且当子数组sum>0时说明该子数组为满足条件的数组。
答案分成两类,整个数组即答案,此时sum(v[0:N]) > 0; 或者是子数组[i:j],此时一定满足sum[v[i:j]] == 1, 因为如果>1,说明该子数组还可以扩张来包含-1的元素,不会是最优解。
找满足sum(v[i:j]) == k的最长子数组,转化成max subarray equals k 问题,用persum求解(hashmap)。
class Solution {
public:
int longestWPI(vector<int>& hours) {
int sum = 0, N = hours.size(), res = 0;
unordered_map<int, int> pre_sums;
for (int i = 0; i < N; ++i) {
sum += hours[i] > 8 ? 1 : -1;
if (sum > 0) res = i + 1;
else {
if (pre_sums.find(sum - 1) != pre_sums.end()) res = max(res, i - pre_sums[sum - 1]);
if (pre_sums.find(sum) == pre_sums.end()) pre_sums[sum] = i;
}
}
return res;
}
};
Last updated
Was this helpful?