1124. Longest Well-Performing Interval

博客围绕给定员工每日工作时长列表,定义了疲劳日和表现良好时间段。目标是求最长表现良好时间段的长度。思路是将工作时长大于8的转化为1,小于8的转化为 -1,把问题转化为求最长子数组使其和大于0,还介绍了利用哈希表处理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值