Python 中最长的良好表现间隔
pythonserver side programmingprogramming更新于 2025/11/13 5:32:17
假设我们有一个小时列表,这是给定员工每天工作小时数的列表。当且仅当工作小时数(严格)大于 8 时,一天才被视为疲劳的一天。一个良好表现间隔是疲劳天数严格大于非疲劳天数的天数间隔。我们必须找到最长的良好表现间隔的长度。因此,如果输入为 [9,9,6,0,6,6,9],则输出将为 3。这是因为最长的良好表现间隔是 [9,9,6]
为了解决这个问题,我们将遵循以下步骤 −
- 设置 temp := 0 和 ans := 0,制作一个映射 d,corner := 0
- 对于 i,范围为 0 到 hours 数组的大小 – 1
- 如果 hours[i] > 8,则 temp := temp + 1,否则为 -1
- 如果 hours[i] > 8,则 corner = 1
- 如果 temp > 0,则 ans := ans 和 i + 1 中的最大值
- 如果 temp 不在映射 d 中,则 d[temp] := i
- 如果 temp – 1 在映射 d 中,则 ans := ans 和 i 中的最大值 – d[temp – 1]
让我们看看下面的实现以便更好地理解 −
示例
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]))
输入
[9,9,6,0,6,6,9]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

