Help in zco16001 bookshelf problem

Hi guys !! I am practising for zco and i came across this problem… i solved it and it worked… but for only few cases :frowning: can someone help me where i went wrong ?

n,k,*s=map(int,input().split())
a=s[:n]
b=s[n:]
s1,s2=a,b
s1.sort()
s2.sort()
ans1=max(s1)+max(s2)
for _ in range(k):
    s1[-1],s2[0]=s2[0],s1[-1]
    s1.sort()
    s2.sort()
    ans1=min(ans1,max(s1)+max(s2))
s1,s2=b,a
s1.sort()
s2.sort()
ans2=max(s1)+max(s2)
for _ in range(k):
    s1[-1],s2[0]=s2[0],s1[-1]
    s1.sort()
    s2.sort()
    ans2=min(ans2,max(s1)+max(s2))
print(min(ans1,ans2))

For the codechef submission here is the link