Editorial for Coconut Canopy
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Each tree at position ni drops coconuts into the two neighboring positions ni−1 and ni+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 k locations. Sorting the values in descending order and summing the largest k entries (or all of them if k>n) maximizes the overnight harvest.
Building the counts takes O(n+m) and the sort dominates with O(nlogn).
A linear-time solution is also possible.
Solution (Python)
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.