Below is my code for the Question in January Long Challenge (FAIRELCT - CODE) FAIR ELECTIONS, Even after getting right output for all the cases my answer is not accepted, Can anyone please help me out here. Thank You
t=int(input())
for t in range (t):
n,m = [int(i) for i in input().split()]
A = list(int(i) for i in input().split())[:n]
B = list(int(i) for i in input().split())[:m]
C=min(len(A),len(B))
count=0
for x in range(C):
if sum(A)<sum(B):
count=count+1
mi=A.index(min(A))
ma=B.index(max(B))
d=max(B)
B[ma]=min(A)
A[mi]=d
if sum(A)<=sum(B):
print("-1")
else:
print(count)
You can include an if condition to check before iteration itself if the sum of votes for A is greater than that for B. if so, just continue to the next test case. And i think the code will make more sense if we use a while loop. Here’s my full AC code:
t = int(input())
for _ in range(t):
n, m = map(int,input().split())
votes_a = list(map(int,input().split()))
votes_b = list(map(int,input().split()))
sum_a = sum(votes_a)
sum_b = sum(votes_b)
if sum_a > sum_b:
print(0)
continue
swaps = 0
flag = False
while(sum_a <= sum_b):
i = votes_a.index(min(votes_a))
j = votes_b.index(max(votes_b))
if(votes_a[i]<votes_b[j]):
votes_a[i],votes_b[j] = votes_b[j],votes_a[i]
diff = abs(votes_a[i]-votes_b[j])
sum_a += diff
sum_b -= diff
swaps += 1
else:
flag = True
break
if flag == True:
print(-1)
else:
print(swaps)
The above is your code. It prints -1 if both arrays have equal sum. Take this test case for example:
1
2 2
5 5
6 4
The correct answer is 1 swap, but your code prints -1.
So as @whitemagic did, you have to convert the sign in the first if statement within the for loop from “<” to “<=”