leetcode 1124. 表现良好的最长时间段(C++、python)

给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。

我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。

所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。

请你返回「表现良好时间段」的最大长度。

 

示例 1:

输入:hours = [9,9,6,0,6,6,9]
输出:3
解释:最长的表现良好时间段是 [9,9,6]。

 

提示:

  • 1 <= hours.length <= 10000
  • 0 <= hours[i] <= 16

思路:大于8,加1,否则,减1;若count大于0,说明从开始到现在,加班的次数大于不加班的次数,此时最大就是count;否则,此时count小于等于0,那么,再看看count-1是否出现过,如果出现过,计算此时count和count-1对应索引的差值。如果count-2存在,那么在它之前count-1一定出现过,因此,第一次出现的count-1和此时的count距离最远。

C++

class Solution {
public:
    int longestWPI(vector<int>& hours) 
    {
        int n=hours.size();
        int res=0;
        int count=0;
        map<int,int> tmp;
        for(int i=0;i<n;i++)
        {
            if(hours[i]>8)
            {
                count++;
            }
            else
            {
                count--;
            }
            if(count>0)
            {
                res=i+1;
            }
            else
            {
                if(tmp.find(count)==tmp.end())
                {
                    tmp[count]=i;
                }
                if(tmp.find(count-1)!=tmp.end())
                {
                    res=max(res,i-tmp[count-1]);
                }
            }            
        }
        return res;
    }
};

python

class Solution:
    def longestWPI(self, hours: List[int]) -> int:
        n=len(hours)
        dic={}
        count=0
        res=0
        for i in range(n):
            if hours[i]>8:
                count+=1
            else:
                count-=1
            if count>0:
                res=i+1
            else:
                if count not in dic:
                    dic[count]=i
                if count-1 in dic:
                    res=max(res,i-dic[count-1])
        return res
                
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值