Задача решена. Код:
with open('27-B.txt') as f:
count_row = int(f.readline())
count_even, count_odd, total_sum = 0, 0, 0
diff_parity_more_less_array = [] # [разница; 10 – разной чётности при большем чётном, 01 – разной чётности при большем нечётном, 00 – одинаковой чётности]
for row in range(count_row):
numbers_array = sorted(list(map(int, f.readline().split())))
max_number = numbers_array[1]
if max_number % 2 == 0:
count_even += 1
else:
count_odd += 1
total_sum += max_number
if (numbers_array[0] + numbers_array[1]) % 2 == 0:
diff_parity_more_less_array.append([abs(numbers_array[0] - numbers_array[1]), '00'])
else:
if numbers_array[1] % 2 == 0:
diff_parity_more_less_array.append([abs(numbers_array[0] - numbers_array[1]), '10'])
else:
diff_parity_more_less_array.append([abs(numbers_array[0] - numbers_array[1]), '01'])
diff_parity_more_less_array = sorted(diff_parity_more_less_array)
i = 0
while True:
if count_even > count_odd and total_sum % 2 != 0 or count_odd > count_even and total_sum % 2 == 0:
total_sum -= diff_parity_more_less_array[i][0]
if diff_parity_more_less_array[i][1] == '01':
count_even += 1
count_odd -= 1
elif diff_parity_more_less_array[i][1] == '10':
count_even -= 1
count_odd += 1
else:
print(total_sum)
break
i += 1
Если есть советы, как оптимизировать, то, пожалуйста, очень буду рад)