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].
Example 2:
Input: hours = [6,6,6] Output: 0
Constraints:
1 <= hours.length <= 104
0 <= hours[i] <= 16
class Solution:
def longestWPI(self, hours: List[int]) -> int:
ans = s = 0
seen = {}
for i, h in enumerate(hours):
s += 1 if h > 8 else -1
if s > 0:
ans = i + 1
else:
if s not in seen:
seen[s] = i
if s - 1 in seen:
ans = max(ans, i - seen[s - 1])
return ans
class Solution {
public int longestWPI(int[] hours) {
int s = 0, ans = 0;
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < hours.length; ++i) {
s += hours[i] > 8 ? 1 : -1;
if (s > 0) {
ans = i + 1;
} else {
seen.putIfAbsent(s, i);
if (seen.containsKey(s - 1)) {
ans = Math.max(ans, i - seen.get(s - 1));
}
}
}
return ans;
}
}
class Solution {
public:
int longestWPI(vector<int>& hours) {
int s = 0, ans = 0;
unordered_map<int, int> seen;
for (int i = 0; i < hours.size(); ++i) {
s += hours[i] > 8 ? 1 : -1;
if (s > 0)
ans = i + 1;
else {
if (!seen.count(s)) seen[s] = i;
if (seen.count(s - 1)) ans = max(ans, i - seen[s - 1]);
}
}
return ans;
}
};
func longestWPI(hours []int) int {
s, ans := 0, 0
seen := make(map[int]int)
for i, h := range hours {
if h > 8 {
s += 1
} else {
s -= 1
}
if s > 0 {
ans = i + 1
} else {
if _, ok := seen[s]; !ok {
seen[s] = i
}
if j, ok := seen[s-1]; ok {
ans = max(ans, i-j)
}
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}