Longest Well-Performing Interval in Python

Suppose we have hours list, this is a list of the number of hours worked per day for a given employee. Here a day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. One 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. We have to find the length of the longest well-performing interval. So if the input is like [9,9,6,0,6,6,9], so then then the output will be 3. This is because the longest well performing interval is [9,9,6]

To solve this, we will follow these steps −

• set temp := 0 and ans := 0, make one map d, and corner := 0
• for i in range 0 to size of hours array – 1
• temp := temp + 1 if hours[i] > 8, otherwise -1
• if hours[i] > 8, then corner = 1
• if temp > 0, then ans := maximum of ans and i + 1
• if temp is not in the map d, then d[temp] := i
• if temp – 1 in the map d, then, ans := maximum of ans and i – d[temp – 1]

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution(object):
def longestWPI(self, hours):
temp = 0
ans = 0
d = {}
corner = 0
for i in range(len(hours)):
temp += 1 if hours[i]>8 else -1
if hours[i]>8:
corner = 1
if temp>0:
ans = max(ans,i+1)
if temp not in d:
d[temp]=i
if temp-1 in d:
ans = max(ans,i-d[temp-1])
return max(ans,0)
ob = Solution()
print(ob.longestWPI([9,9,6,0,6,6,9]))

Input

[9,9,6,0,6,6,9]

Output

3