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].
Constraints:
1 <= hours.length <= 10000
0 <= hours[i] <= 16
思路:>8的转化为1,<8的转化为-1
于是题目就变成求最长的subarray,使得该subarray的和大于0
如果是等于0,直接hashtable查找就行
大于0需要变一下,还是做从0开始的running sum,用hashtable记录负的sum,
假设遍历到index位置,从0开始的running sum为-1,那就从hashtable里面找-2(所以存的时候-2一定要存数组索引最小的,转化到代码就是如果-2已经在hashtable就不更新),这样中间的区间sum就为1
为什么不找-3,-4呢?因为他们不会出现在-2的前面(-2过了才能减到-3,而-2是最优的)
class Solution(object):
def longestWPI(self, hours):
"""
:type hours: List[int]
:rtype: int
"""
helper = [1 if a>8 else -1 for a in hours]
d = {}
res = 0
running = 0
for i,a in enumerate(helper):
running += a
if running>0:
res=max(res,i+1)
else:
if running-1 in d:
res=max(res,i-d[running-1])
if running not in d: d[running]=i
return res