Skip to content

Commit 8303698

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (83.73%), Memory - 18.3 MB (12.57%)
1 parent d211a8c commit 8303698

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You want to find a <strong>subsequence </strong>of <code>nums</code> of length <code>k</code> that has the <strong>largest</strong> sum.</p>
2+
3+
<p>Return<em> </em><em><strong>any</strong> such subsequence as an integer array of length </em><code>k</code>.</p>
4+
5+
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [2,1,3,3], k = 2
12+
<strong>Output:</strong> [3,3]
13+
<strong>Explanation:</strong>
14+
The subsequence has the largest sum of 3 + 3 = 6.</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [-1,-2,3,4], k = 3
20+
<strong>Output:</strong> [-1,3,4]
21+
<strong>Explanation:</strong>
22+
The subsequence has the largest sum of -1 + 3 + 4 = 6.
23+
</pre>
24+
25+
<p><strong class="example">Example 3:</strong></p>
26+
27+
<pre>
28+
<strong>Input:</strong> nums = [3,4,3,3], k = 2
29+
<strong>Output:</strong> [3,4]
30+
<strong>Explanation:</strong>
31+
The subsequence has the largest sum of 3 + 4 = 7.
32+
Another possible subsequence is [4, 3].
33+
</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
40+
<li><code>-10<sup>5</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
41+
<li><code>1 &lt;= k &lt;= nums.length</code></li>
42+
</ul>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Approach: Sorting
2+
3+
# Time: O(n log n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
8+
n = len(nums)
9+
vals = [(i, nums[i]) for i in range(n)]
10+
vals.sort(key=lambda x: -x[1]) # Sort in descending order of nums
11+
vals = sorted(vals[:k]) # Pick first k elements and sorted in ascending order by index
12+
res = [val for idx, val in vals]
13+
return res
14+

0 commit comments

Comments
 (0)