Input: nums =[2,4,-2], k =5Output: 2Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:-6,4,4,2, _2_ ,0,0,-2.The 5-Sum of the array is2.
The largest possible subsequence sum is the sum of all positive numbers. To find the k-th largest, we can sort the absolute values, use a max-heap to generate possible sums by removing elements, and always expand the next largest sum by removing the next smallest absolute value. This is similar to finding the k-th largest sum in a sorted array of subset sums.
classSolution {
public:longlong kSum(vector<int>& nums, int k) {
longlong total =0;
for (int&x : nums) if (x >0) total += x;
vector<longlong> arr;
for (int x : nums) arr.push_back(abs(x));
sort(arr.begin(), arr.end());
priority_queue<pair<longlong, int>> pq;
set<pair<longlong, int>> seen;
pq.push({total, 0});
seen.insert({0, 0});
longlong ans = total;
while (--k) {
auto [sum, i] = pq.top(); pq.pop();
if (i < arr.size()) {
pq.push({sum - arr[i], i +1});
if (i >0) pq.push({sum - arr[i] + arr[i-1], i +1});
}
ans = sum;
}
return ans;
}
};
classSolution {
publiclongkSum(int[] nums, int k) {
long total = 0;
for (int x : nums) if (x > 0) total += x;
int[] arr =newint[nums.length];
for (int i = 0; i < nums.length; ++i) arr[i]= Math.abs(nums[i]);
Arrays.sort(arr);
PriorityQueue<long[]> pq =new PriorityQueue<>((a, b) -> Long.compare(b[0], a[0]));
pq.offer(newlong[]{total, 0});
long ans = total;
while (k--> 0) {
long[] cur = pq.poll();
ans = cur[0];
int i = (int)cur[1];
if (i < arr.length) {
pq.offer(newlong[]{cur[0]- arr[i], i + 1});
if (i > 0) pq.offer(newlong[]{cur[0]- arr[i]+ arr[i-1], i + 1});
}
}
return ans;
}
}
classSolution {
funkSum(nums: IntArray, k: Int): Long {
var total = 0Lfor (x in nums) if (x > 0) total += x
val arr = nums.map { Math.abs(it) }.sorted()
val pq = PriorityQueue<Pair<Long, Int>>(compareByDescending { it.first })
pq.add(Pair(total, 0))
var ans = total
var kk = k
while (kk-- > 0) {
val(sum, i) = pq.poll()
ans = sum
if (i < arr.size) {
pq.add(Pair(sum - arr[i], i + 1))
if (i > 0) pq.add(Pair(sum - arr[i] + arr[i-1], i + 1))
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import heapq
classSolution:
defkSum(self, nums: list[int], k: int) -> int:
total = sum(x for x in nums if x >0)
arr = sorted(abs(x) for x in nums)
h = [(-total, 0)]
seen = set()
seen.add((0, 0))
ans = total
for _ in range(k):
s, i = heapq.heappop(h)
ans =-s
if i < len(arr):
heapq.heappush(h, (s + arr[i], i +1))
if i >0:
heapq.heappush(h, (s + arr[i] - arr[i-1], i +1))
return ans