Longest Well-Performing Interval Problem
Description
LeetCode Problem 1124.
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 <= 10^40 <= hours[i] <= 16
Solution
Approach: Prefix Score and First Occurrences
Score each day +1 if it is tiring (hours[i] > 8) and -1 otherwise. An interval is well-performing exactly when its scores add up to more than 0. With a running prefix score score, an interval (j, i] works when score_i - score_j > 0, so for each i we want the earliest j with a smaller prefix score.
Two cases:
- If
score > 0, the whole prefixhours[0..i]works, and nothing can be longer, so the length isi + 1. - Otherwise, look for the first index where the prefix score was
score - 1. That is enough: the score starts at 0 and moves by exactly 1 per day, so to ever go belowscore - 1it must pass throughscore - 1first. The firstscore - 1therefore comes before any smaller value, and it gives the longest interval ending ati.
A hash map stores the first index of each prefix score. Only write a score in the first time it appears; overwriting it with a later index would make the intervals shorter.
Complexity: O(n) time and O(n) extra space for the map.
class Solution:
def longestWPI(self, hours: List[int]) -> int:
best = score = 0 # score = tiring days minus other days so far
first = {} # score -> first index where the prefix had that score
for i, h in enumerate(hours):
score += 1 if h > 8 else -1
if score > 0:
best = i + 1 # the whole prefix is well-performing
elif score - 1 in first:
best = max(best, i - first[score - 1])
if score not in first:
first[score] = i
return best