comments | difficulty | edit_url | rating | source | tags | ||||
---|---|---|---|---|---|---|---|---|---|
true |
Easy |
1447 |
Biweekly Contest 67 Q1 |
|
You are given an integer array nums
and an integer k
. You want to find a subsequence of nums
of length k
that has the largest sum.
Return any such subsequence as an integer array of length k
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [2,1,3,3], k = 2 Output: [3,3] Explanation: The subsequence has the largest sum of 3 + 3 = 6.
Example 2:
Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Explanation: The subsequence has the largest sum of -1 + 3 + 4 = 6.
Example 3:
Input: nums = [3,4,3,3], k = 2 Output: [3,4] Explanation: The subsequence has the largest sum of 3 + 4 = 7. Another possible subsequence is [4, 3].
Constraints:
1 <= nums.length <= 1000
-105 <= nums[i] <= 105
1 <= k <= nums.length
First, we create an index array
After sorting, we take the last
The time complexity is
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
idx = sorted(range(len(nums)), key=lambda i: nums[i])[-k:]
return [nums[i] for i in sorted(idx)]
class Solution {
public int[] maxSubsequence(int[] nums, int k) {
int n = nums.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; ++i) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> nums[i] - nums[j]);
Arrays.sort(idx, n - k, n);
int[] ans = new int[k];
for (int i = n - k; i < n; ++i) {
ans[i - (n - k)] = nums[idx[i]];
}
return ans;
}
}
func maxSubsequence(nums []int, k int) []int {
n := len(nums)
idx := make([]int, n)
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(i, j int) bool { return nums[idx[i]] < nums[idx[j]] })
sort.Ints(idx[n-k:])
ans := make([]int, k)
for i := n - k; i < n; i++ {
ans[i-(n-k)] = nums[idx[i]]
}
return ans
}
function maxSubsequence(nums: number[], k: number): number[] {
const n = nums.length;
const idx: number[] = Array.from({ length: n }, (_, i) => i);
idx.sort((i, j) => nums[i] - nums[j]);
return idx
.slice(n - k)
.sort((i, j) => i - j)
.map(i => nums[i]);
}