You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2300-2399/2386.Find the K-Sum of an Array/README_EN.md
+21-10
Original file line number
Diff line number
Diff line change
@@ -47,19 +47,31 @@ The 5-Sum of the array is 2.
47
47
48
48
## Solutions
49
49
50
-
### Solution 1
50
+
### Solution 1: Priority Queue (Min Heap)
51
+
52
+
First, we find the maximum subsequence sum $mx$, which is the sum of all positive numbers.
53
+
54
+
It can be found that the sum of other subsequences can be regarded as the maximum subsequence sum, minus the sum of other part of the subsequence. Therefore, we can convert the problem into finding the $k$-th smallest subsequence sum.
55
+
56
+
We only need to sort all numbers in ascending order by their absolute values, then establish a min heap, storing pairs $(s, i)$, representing the current sum is $s$, and the index of the next number to be selected is $i$.
57
+
58
+
Each time we take out the top of the heap, and put in two new situations: one is to select the next position, and the other is to select the next position and not select this position.
59
+
60
+
Since the array is sorted from small to large, this method can traverse all subsequence sums in order without duplication.
61
+
62
+
The time complexity is $O(n \times \log n + k \times \log k)$, where $n$ is the length of the array `nums`, and $k$ is the given $k$ in the problem.
0 commit comments