Skip to content

Commit 2bcc7b3

Browse files
authored
Create maximum-tastiness-of-candy-basket.py
1 parent a2eb491 commit 2bcc7b3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(nlogr), r = max(price)-min(price)
2+
# Space: O(1)
3+
4+
# binary search, greedy
5+
class Solution(object):
6+
def maximumTastiness(self, price, k):
7+
"""
8+
:type price: List[int]
9+
:type k: int
10+
:rtype: int
11+
"""
12+
def check(x): # max cnt if smallest absolute difference >= x
13+
cnt = prev = 0
14+
for i in xrange(len(price)):
15+
if prev and price[i]-prev < x:
16+
continue
17+
cnt += 1
18+
if cnt == k:
19+
break
20+
prev = price[i]
21+
return cnt >= k
22+
23+
price.sort()
24+
left, right = 1, price[-1]-price[0]
25+
while left <= right:
26+
mid = left + (right-left)//2
27+
if not check(mid):
28+
right = mid-1
29+
else:
30+
left = mid+1
31+
return right

0 commit comments

Comments
 (0)