左向右列表python任务

问题描述 投票:0回答:1

这是我试图解决的任务

丹尼斯是一位真正的研究员,他在大学的日子充满了讲座、实验和报告。他学习勤奋,但像所有学生一样,有时也会犯错误,成绩也不是最高。 今天,丹尼斯面临着一个特殊的挑战 - 他需要向他的研究主管提供他的报告。教授要求连续7天看他的所有作品。成绩以 2 到 5 之间的整数序列表示 - 每天一个成绩。 Denis希望选择这样一个连续的时间段进行报告,使得该时间段内没有2级和3级的作品,并且5级的作品数量最多。 帮助丹尼斯找到这个特殊的时刻,让他的科学之光战胜黑暗,让他的作品闪闪发光!

输入格式 第一行包含一个自然数 n - 报告数量 (1 ≤ n ≤ 10^5)。第二行包含整数 - 每天一个等级 (2 ≤ m ≤ 5)。

输出格式 输出Denis选择的选定时间段内满足所有条件的优秀报告数量。如果这样的周期不存在,则输出-1。

我写了这段代码,但我不明白问题是什么。我将不胜感激任何帮助。如果您也给我一个代码示例,那么我会很高兴。提前谢谢大家。

n = int(input())
grades = list(map(int, input().split()))

left = 0
max_fives = 0
current_fives = 0

while left < n and (grades[left] == 2 or grades[left] == 3):
    left += 1

for right in range(left, n):
    if grades[right] == 5:
        current_fives += 1

    while grades[right] == 2 or grades[right] == 3:
        left += 1

    max_fives = max(max_fives, current_fives)

    if right - left >= 6:
        if grades[left] == 5:
            current_fives -= 1
        left += 1

if max_fives == 0:
    print(-1)
else:
    print(max_fives)

这里有 3 个测试

Input
9
5 5 4 5 4 5 4 5 4
Output
4
Input
8
3 4 4 4 4 5 4 5
Output
2
Input
10
5 5 5 5 5 3 5 5 5 5
Output
-1

第三次检查时一切都崩溃了。

python list algorithm arraylist
1个回答
0
投票

您尝试调整初始左侧位置以绕过 2 级或 3 级,这很好,但您还需要确保当此类等级广泛存在时,这不会忽略整个数组处理。每当遇到 2 级或 3 级时向左递增的逻辑可能会错误地跳过元素,因为它不能确保在跳过元素时正确处理 current_ Fives 计数调整。您的代码无法正确确保窗口大小恰好为 7,也无法在遇到 2 或 3 级时正确重置或调整窗口。当 2 级或 3 级导致移位时,基于左边界的 current_ Fives 的减少没有得到正确处理。

n = int(input())
grades = list(map(int, input().split()))

left = 0
max_fives = 0
current_fives = 0
valid_period = False

while left < n:
    while left < n and (grades[left] == 2 or grades[left] == 3):
        left += 1

    right = left
    current_fives = 0
    
    while right < n and right - left < 7:
        if grades[right] == 2 or grades[right] == 3:
            left = right + 1
            current_fives = 0
        else:
            if grades[right] == 5:
                current_fives += 1
            right += 1
    
    if right - left == 7:
        valid_period = True
        max_fives = max(max_fives, current_fives)
        if grades[left] == 5:
            current_fives -= 1
        left += 1

print(max_fives if valid_period else -1)
© www.soinside.com 2019 - 2024. All rights reserved.