-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxProfit.py
More file actions
43 lines (37 loc) · 1.36 KB
/
maxProfit.py
File metadata and controls
43 lines (37 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import heapq
class Solution:
def maxProfit(self, inventory: List[int], orders: int) -> int:
if not inventory or not orders:
return 0
inventory.sort(reverse=True)
fullfillPos = self.binarySearch(inventory, orders)
ans = 0
for inv in inventory:
if inv >= fullfillPos:
ans += (fullfillPos + inv) * (inv - fullfillPos + 1) // 2
else:
break
fullfilled = self.calcNumFullfilled(inventory, fullfillPos)
if fullfilled < orders and fullfillPos > 1:
ans += (orders - fullfilled) * (fullfillPos-1)
return ans % (10 ** 9 + 7)
def binarySearch(self, inventory, orders):
low, high = 1, inventory[0]
while low + 1 < high:
mid = (low + high) // 2
fullfilled = self.calcNumFullfilled(inventory, mid)
if fullfilled < orders:
high = mid
else:
low = mid
if self.calcNumFullfilled(inventory, low) <= orders:
return low
return high
def calcNumFullfilled(self, inventory, mid):
fullfilled = 0
for inv in inventory:
if inv >= mid:
fullfilled += inv - mid + 1
else:
break
return fullfilled