Counting by 10s — Solution
For this problem, we seek an solution since .
We can approach this problem by first finding the correct sum, then finding the sum Stephan computed, and then subtract the two values.
Finding the correct sum is straightforward; we just sum the input array.
In terms of finding the sum Stephan computed, we notice that there is a forced decision. Since the only numbers available are , there is only one other number for every number from to that adds to . (More specifically, MUST go with , MUST go with , MUST go with , MUST go with , and must go with .)
As a result, for every number to , the question becomes: What is the maximum number of pairs that this number can make with the only other number that makes ? The answer to that is the minimum of the frequencies of the two numbers.
For example, let’s say we had this set: . We can group all the s with a , so we make pairs. But the two remaining ’s won’t have a to go with (due to the forced decision), so the answer is . The same holds true for all and such that .
As a result, the answer just becomes , where denotes the frequency of , for all . (Note that the upper bound for here is , NOT , because we would be double-counting each pair that way.)
For , we can proceed with taking the minimum of the two frequencies. However, is a special case. Note that pairs with itself, so we can make at most pairs of when we have 5s.
Finally, we multiply our result by , since doing the processes above will only give us the number of pairs and that each pair will always add to , and we get Stephan’s sum.
This solution is indeed fast enough. It runs in time, as summing the array and finding the frequency of each element takes time, and iterating through the frequency count takes time.
So, we conclude by subtracting the sum of the array with Stephan’s sum computed above, and we have our answer!
Python implementation
n = int(input())
nums = list(map(int,input().split()))
s = 0
occs = {}
for i in range(1, 10):
occs[i] = 0
for i in range(n):
s += nums[i]
occs[nums[i]] += 1
stephans_ans = 0
for i in range(1, 6):
if i != 5:
stephans_ans += (min(occs[i], occs[10-i])*10)
else:
stephans_ans += (int(occs[i]/2)*10)
print(s-stephans_ans)