Longest Well-Performing Interval
Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].Thoughts
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