Can someone help me with this problem?

Правка en1, от infj1, 2023-12-03 07:45:57

Given an array of length n containing only zeros and ones, you can perform operations by removing either the first or the last element of the array. Calculate the minimum number of operations required to achieve a total sum of s in the array. If it is not possible to obtain the sum s after any number of operations, the output should be -1.

The code below is my approach. But when I submit its giving wrong answer. Could you guys what's the problem with the code? Or the approach?

for _ in range(int(input())): n,s=[int(i) for i in input().split()] a=[int(i) for i in input().split()] c=0 for i in range(n):

if a[i]==1:
        c+=1


if c<s:
    print(-1)
else:
    l=0
    r=n-1
    req=c-s
    got=0
    ans=0
    if got==req:
        print(0)
        continue
    while l<r and got<req:
        old_l=l
        while l<r and a[l]==0:
            l+=1
        old_r=r
        while r>l and a[r]==0:
            r-=1
        l_dis=l-old_l
        r_dis=old_r-r
        if l_dis<r_dis:
            r=old_r
            ans+=l_dis+1
            l+=1
        else:
            l=old_l
            ans+=r_dis+1
            r-=1
        got+=1
    print(ans)
Теги problem

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский infj1 2023-12-03 07:47:34 10
en1 Английский infj1 2023-12-03 07:45:57 1418 Initial revision (published)