1defgetMinimumCost(k, c):2 numFlowers =len(c)3# if numFlowers <= k: sort c in ascending order and return the sum of c[:numFlowers]4# else:5# for i in range(k): add the most expensive flowers and numFlowers -= 16# for i in range(numFlowers): add the least expensive flowers and numFlowers -= 17 c.sort()8if numFlowers <= k:returnsum(c[:numFlowers])9else:10 res, lastFlower =0,len(c)-111 kBought =[]12for i inrange(k):13 res += c[-(i +1)]14 heappush(kBought,1)15 lastFlower -=116 numFlowers -=11718 i = lastFlower
19while numFlowers >0:20 minKBoughtFlowers = heappop(kBought)21 res +=(minKBoughtFlowers +1)* c[lastFlower]22 heappush(kBought, minKBoughtFlowers +1)23 lastFlower -=124 numFlowers -=12526return res