返回介绍

solution / 2000-2099 / 2099.Find Subsequence of Length K With the Largest Sum / README_EN

发布于 2024-06-17 01:03:10 字数 3774 浏览 0 评论 0 收藏 0

2099. Find Subsequence of Length K With the Largest Sum

中文文档

Description

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

Solutions

Solution 1

class Solution:
  def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
    idx = list(range(len(nums)))
    idx.sort(key=lambda i: nums[i])
    return [nums[i] for i in sorted(idx[-k:])]
class Solution {
  public int[] maxSubsequence(int[] nums, int k) {
    int[] ans = new int[k];
    List<Integer> idx = new ArrayList<>();
    int n = nums.length;
    for (int i = 0; i < n; ++i) {
      idx.add(i);
    }
    idx.sort(Comparator.comparingInt(i -> - nums[i]));
    int[] t = new int[k];
    for (int i = 0; i < k; ++i) {
      t[i] = idx.get(i);
    }
    Arrays.sort(t);
    for (int i = 0; i < k; ++i) {
      ans[i] = nums[t[i]];
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> maxSubsequence(vector<int>& nums, int k) {
    int n = nums.size();
    vector<pair<int, int>> vals;
    for (int i = 0; i < n; ++i) vals.push_back({i, nums[i]});
    sort(vals.begin(), vals.end(), [&](auto x1, auto x2) {
      return x1.second > x2.second;
    });
    sort(vals.begin(), vals.begin() + k);
    vector<int> ans;
    for (int i = 0; i < k; ++i) ans.push_back(vals[i].second);
    return ans;
  }
};
func maxSubsequence(nums []int, k int) []int {
  idx := make([]int, len(nums))
  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[:k])
  ans := make([]int, k)
  for i, j := range idx[:k] {
    ans[i] = nums[j]
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文