1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows
Description
You are given an m x n
matrix mat
that has its rows sorted in non-decreasing order and an integer k
.
You are allowed to choose exactly one element from each row to form an array.
Return the kth
smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5 Output: 7 Explanation: Choosing one element from each row, the first k smallest sum are: [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9 Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7 Output: 9 Explanation: Choosing one element from each row, the first k smallest sum are: [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i]
is a non-decreasing array.
Solutions
Solution: Queue
- Time complexity: O(nlogn)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[][]} mat
* @param {number} k
* @return {number}
*/
const kthSmallest = function (mat, k) {
const m = mat.length;
const n = mat[0].length;
let currentSums = mat[0];
const kSmallestSums = (nums1, nums2, k) => {
const minHeap = new MinPriorityQueue({ priority: ({ sum }) => sum });
const result = [];
for (const [index, element] of nums1.entries()) {
const sum = element + nums2[0];
minHeap.enqueue({ a: index, b: 0, sum });
}
while (minHeap.size() && result.length < k) {
const { a, b, sum } = minHeap.dequeue().element;
result.push(sum);
if (b + 1 < n) {
const nextSum = nums1[a] + nums2[b + 1];
minHeap.enqueue({ a, b: b + 1, sum: nextSum });
}
}
return result;
};
for (let row = 1; row < m; row++) {
currentSums = kSmallestSums(currentSums, mat[row], k);
}
return currentSums[k - 1];
};