Skip to content

Commit 2c83185

Browse files
authored
Create find-subsequence-of-length-k-with-the-largest-sum.py
1 parent 5f59191 commit 2c83185

File tree

1 file changed

+50
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)