class Solution:
def maxProfit(self, inventory: List[int], n: int) -> int:
# n is the number of balls client wants
# O(nlogn) for the sort part, space O(1)
# A 先拿上面2个A , 接着AB可以一起拿
# A
# A B
# A B
inventory.sort(reverse=True)
inventory.append(0)
res = 0
k = 1 # number of differnet balls with max size
# print(inventory)
for i in range(len(inventory) - 1):
# print(i)
if inventory[i] > inventory[i+1]:
diff = inventory[i] - inventory[i+1]
# print("k*dff, n", k*diff, n)
if k * diff < n:
res += k * (inventory[i] + inventory[i+1] + 1) * diff // 2 # 首项与末项的和项数除以2
n -= k*diff
# print("n, res", n, res)
else:
q, r = divmod(n, k) # 总共k排,每排拿q个 还要额外拿r个
res += k*(inventory[i] + (inventory[i] - q+1)) * q // 2
res += r*(inventory[i] - q)
return res % (10**9+7)
k += 1 # k 要一直加一
1921. Eliminate Maximum Number of Monsters
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
# h = []
# for i, d in enumerate(dist):
# needT = d // speed[i]
# if d % speed[i]: # round up
# needT += 1
# heapq.heappush(h, needT)
# re = usedT = 0
# while h:
# needT = heapq.heappop(h)
# needT -= usedT
# if needT <= 0:
# return re
# re += 1
# usedT += 1
# return re
for i, d in enumerate(dist):
needT = d // speed[i]
if d % speed[i]:
needT += 1 # round up
dist[i] = needT
dist.sort()
for i, v in enumerate(dist):
if i >= v:
return i
return len(dist)
1798. Maximum Number of Consecutive Values You Can Make
class Solution:
def getMaximumConsecutive(self, coins: List[int]) -> int:
'''
1113
0, 1, 11, 111, 31, 322, 3111
Initialize res = 1 since we count from 0;
Sort coins;
For each coin in coins:
if coin > res, then the consecutive values cannot expand to the right;
if coin == res, then the consecutive values can be just perfectly expanded, res = coin + res;
if coin < res, then the consecutive values can be expanded, but not as "efficient" as a