[LeetCode] Find the Kth Smallest Sum of a Matrix With Sorted Rows

1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

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.

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
class Solution {
int getCount(vector<vector<int>>& mat, int& mid, int& k, int row = 0, int sum = 0) {
if(sum > mid) return 0;
if(row == mat.size()) return 1;
int res = 0;
for(auto& num : mat[row]) {
int ans = getCount(mat, mid, k, row + 1, sum + num);
if(!ans) break;
res += ans;
if(res > k) break;
}
return res;
}
public:
int kthSmallest(vector<vector<int>>& mat, int k) {
int l = 0, r = INT_MAX, n = mat.size(), m = mat[0].size();
while(l <= r) {
int m = l + (r-l) / 2;

int c = getCount(mat, m, k);

if(c >= k) r = m - 1;
else l = m + 1;


}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/14/PS/LeetCode/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.