Skip to content

Commit c15c011

Browse files
authored
Create mice-and-cheese.py
1 parent 9ac4d5b commit c15c011

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Python/mice-and-cheese.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
import random
5+
6+
7+
# greedy, quick select
8+
class Solution(object):
9+
def miceAndCheese(self, reward1, reward2, k):
10+
"""
11+
:type reward1: List[int]
12+
:type reward2: List[int]
13+
:type k: int
14+
:rtype: int
15+
"""
16+
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
17+
def tri_partition(nums, left, right, target, compare):
18+
mid = left
19+
while mid <= right:
20+
if nums[mid] == target:
21+
mid += 1
22+
elif compare(nums[mid], target):
23+
nums[left], nums[mid] = nums[mid], nums[left]
24+
left += 1
25+
mid += 1
26+
else:
27+
nums[mid], nums[right] = nums[right], nums[mid]
28+
right -= 1
29+
return left, right
30+
31+
right = len(nums)-1
32+
while left <= right:
33+
pivot_idx = random.randint(left, right)
34+
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
35+
if pivot_left <= n <= pivot_right:
36+
return
37+
elif pivot_left > n:
38+
right = pivot_left-1
39+
else: # pivot_right < n.
40+
left = pivot_right+1
41+
42+
for i in xrange(len(reward1)):
43+
reward1[i] -= reward2[i]
44+
nth_element(reward1, k-1, compare=lambda a, b: a > b)
45+
return sum(reward2)+sum(reward1[i] for i in xrange(k))

0 commit comments

Comments
 (0)