Editorial for Coconut Canopy


Approach

Each tree at position nin_i drops coconuts into the two neighboring positions ni−1n_i - 1 and ni+1n_i + 1. We can therefore compute, for every street position, how many coconuts would land there if we placed a basket on that slot. Now, we only need the to sum the values of the top kk locations. Sorting the values in descending order and summing the largest kk entries (or all of them if k>nk > n) maximizes the overnight harvest.

Building the counts takes O(n+m)O(n + m) and the sort dominates with O(nlog⁡n)O(n \log n).

A linear-time solution is also possible.

Solution (Python)

Code 1
n,m,k = map(int,input().split())
locs= list(map(int,input().split()))

cocs = [0 for i in range(n)]
for i in locs:
    loc = i-1
    if(0 <= loc-1 < len(cocs)):
        cocs[loc-1] += 1
    
    if(0 <= loc+1 < len(cocs)):
        cocs[loc+1] +=1

cocs.sort(reverse=True)

i = 0
ans = 0
while (i < k and i < len(cocs)):
    ans += cocs[i]
    i+= 1

print(ans)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.