ANCO

Counting by 10s — Solution

For this problem, we seek an O(N)O(N) solution since N≤105N \leq 10^5.
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 1…91 \ldots 9, there is only one other number for every number from 11 to 99 that adds to 1010. (More specifically, 11 MUST go with 99, 22 MUST go with 88, 33 MUST go with 77, 44 MUST go with 66, and 55 must go with 55.)
As a result, for every number 11 to 99, the question becomes: What is the maximum number of pairs that this number can make with the only other number that makes 1010? The answer to that is the minimum of the frequencies of the two numbers.
For example, let’s say we had this set: [4,4,4,6,6,6,6,6][4, 4, 4, 6, 6, 6, 6, 6]. We can group all the 44s with a 66, so we make 33 (4,6)(4, 6) pairs. But the two remaining 66’s won’t have a 44 to go with (due to the forced decision), so the answer is min⁡(freq(4),freq(6))=3\min(\text{freq}(4), \text{freq}(6)) = 3. The same holds true for all xx and 10−x10-x such that 1≤x≤91 \leq x \leq 9.
As a result, the answer just becomes min⁡(freq(x),freq(10−x))\min(\text{freq}(x), \text{freq}(10-x)), where freq(x)\text{freq}(x) denotes the frequency of xx, for all 1≤x≤51 \leq x \leq 5. (Note that the upper bound for xx here is 55, NOT 1010, because we would be double-counting each pair that way.)
For 1≤x≤41 \leq x \leq 4, we can proceed with taking the minimum of the two frequencies. However, x=5x=5 is a special case. Note that 55 pairs with itself, so we can make at most ⌊n/2⌋\lfloor n/2 \rfloor pairs of (5,5)(5, 5) when we have nn 5s.
Finally, we multiply our result by 1010, since doing the processes above will only give us the number of pairs and that each pair will always add to 1010, and we get Stephan’s sum.
This solution is indeed fast enough. It runs in O(N)O(N) time, as summing the array and finding the frequency of each element takes O(N)O(N) time, and iterating through the frequency count takes O(1)O(1) 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)
← Back to problem