【发布时间】:2020-12-28 15:49:01
【问题描述】:
这是 geeksforgeeks 问题的链接 https://practice.geeksforgeeks.org/problems/maximum-distinct-elements-after-removing-k-elements/0
这是我的代码-
import collections
import heapq
def maxoccur(arr,k):
c = 0
d = collections.Counter(arr)
heap = [(value,key) for key,value in d.items()]
heapq.heapify(heap)
while(heap):
x = heapq.heappop(heap)
if x[0] == 1:
c+=1
elif x[0]>1 and k>0:
k-=1
y = x[0]-1
heapq.heappush(heap,(y,x[1]))
elif k<=0:
break
if k == 0:
while(heap):
x = heapq.heappop(heap)
if x[0] == 1:
c+=1
elif k>0:
c-=k
return c
我的代码有什么问题我在这个测试用例中得到了错误的答案-
输入: 84 47 28 26 24 26 17 13 10 2 3 8 21 20 24 17 1 7 23 17 12 9 28 10 3 21 3 14 8 26 30 13 13 19 30 28 14 17 2 23 10 4 22 30 15 8 9 15 6 2 21 27 4 3 21 17 2 16 16 15 28 27 6 17 10 14 18 25 16 13 16 15 28 15 15 4 21 8 19 7 9 9 25
它的正确输出是: 27
您的代码的输出是: 25
【问题讨论】:
标签: python-3.x algorithm data-structures hash heap