[LeetCode] Find the K-Sum of an Array

2386. Find the K-Sum of an Array

You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.

We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).

Return the K-Sum of the array.

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.

Note that the empty subsequence is considered to have a sum of 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
long long kSum(vector<int>& A, int k) {
long long sum = 0, n = A.size();
for(auto& a : A) {
if(a > 0) {
sum += a;
a = -a;
}
}
sort(rbegin(A), rend(A));
priority_queue<pair<long long, long long>> q;
priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> rq;
q.push({0,-1});
rq.push({0,-1});
long long K = k;
while(--K) {
auto [now, bound] = q.top(); q.pop();
for(int i = bound + 1; i < n; i++) {
if(rq.size() > k) {
if(now + A[i] > rq.top().first) {
rq.push({now + A[i], i});
q.push({now + A[i], i});
} else break;
} else if(rq.size() <= k){
rq.push({now + A[i], i});
q.push({now + A[i], i});
}
}
while(rq.size() > k) rq.pop();
}

return sum + q.top().first;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/21/PS/LeetCode/find-the-k-sum-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.