# 2099. Find Subsequence of Length K With the Largest Sum [2099. Find Subsequence of Length K With the Largest Sum](https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum) (<font color="#00AF9B"> Easy</font> 通過率: 44.5%) ## 限制條件 <ul> <li>1 <= nums.length <= 1000</li> <li>-10^5 <= nums[i] <= 10^5</li> <li>1 <= k <= nums.lengt</li> </ul> ### 解法 1 這一題要找的是前 k 個最大的數字,並且相同時以出現較早的為主。 解法是運用 priority_queue 先將最大的 k 數字撿起來,再把 index和 value 對調 運用 priority_queue 排 index 的先後順序 - 時間複雜度: O(nlogn) - 空間複雜度: O(N) ```cpp!= class Solution { public: vector<int> maxSubsequence(vector<int>& nums, int k) { priority_queue<pair<int, int>> records; for (int i = 0; i < nums.size(); i++) { records.emplace(nums[i], i); } priority_queue<pair<int, int>> result_heap; vector<int> results(k); for (int i = 0; i < k; i++) { auto [value, index] = records.top(); records.pop(); result_heap.emplace(index, value); } for (int i = 0; i < k; i++) { auto [index, value] = result_heap.top(); result_heap.pop(); results[k - 1 - i] = value; } return results; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up