class Solution {
public:
int longestWPI(vector<int>& hours) {
unordered_map<int, int> prefixMap;
prefixMap[0] = -1;
int res = 0;
for (int i = 0, sum = 0; i < hours.size(); i++) {
sum += hours[i] > 8 ? 1 : -1;
if (sum > 0) {
res = i + 1;
} else {
if (prefixMap.find(sum - 1) != prefixMap.end()) {
res = max(res, i - prefixMap[sum - 1]);
}
}
if (prefixMap.find(sum) == prefixMap.end()) {
prefixMap[sum] = i;
}
}
return res;
}
};