给你一份工作时间表 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