forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-alloys.py
74 lines (68 loc) · 2.21 KB
/
maximum-number-of-alloys.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Time: O(k * nlogn)
# Space: O(n)
# sort, math
class Solution(object):
def maxNumberOfAlloys(self, n, k, budget, composition, stock, cost):
"""
:type n: int
:type k: int
:type budget: int
:type composition: List[List[int]]
:type stock: List[int]
:type cost: List[int]
:rtype: int
"""
def count(machine, budget):
def cnt(x):
return stock[x]//machine[x]
idxs = range(n)
idxs.sort(key=cnt)
result = cnt(idxs[0])
prefix = curr = discount = 0
for i in xrange(n):
curr += cost[idxs[i]]*machine[idxs[i]]
discount += cost[idxs[i]]*(stock[idxs[i]]%machine[idxs[i]])
if i+1 != n and cnt(idxs[i+1])-cnt(idxs[i]) == 0:
continue
prefix += curr
budget += discount
curr = discount = 0
mn = min((cnt(idxs[i+1])-cnt(idxs[i]) if i+1 < n else float("inf")), budget//prefix)
if mn == 0:
break
budget -= prefix*mn
result += mn
return result
return max(count(machine, budget) for machine in composition)
# Time: O(k * n * logr), r = min(stock)+budget
# Space: O(1)
# binary search
class Solution2(object):
def maxNumberOfAlloys(self, n, k, budget, composition, stock, cost):
"""
:type n: int
:type k: int
:type budget: int
:type composition: List[List[int]]
:type stock: List[int]
:type cost: List[int]
:rtype: int
"""
def check(x):
for machine in composition:
curr = 0
for i in xrange(n):
curr += max(x*machine[i]-stock[i], 0)*cost[i]
if curr > budget:
break
if curr <= budget:
return True
return False
left, right = 1, min(stock)+budget
while left <= right:
mid = left+(right-left)//2
if not check(mid):
right = mid-1
else:
left = mid+1
return right