[LeetCode] Find Valid Matrix Given Row and Column Sums

1605. Find Valid Matrix Given Row and Column Sums

You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.

Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.

Return a 2D array representing any matrix that fulfills the requirements. It’s guaranteed that at least one matrix that fulfills the requirements exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<vector<int>> restoreMatrix(vector<int>& r, vector<int>& c) {
int n = r.size(), m = c.size();
vector<vector<int>> res(n, vector<int>(m));
for(int i = 0; i < n; i++) {
for(int j = 0, now = r[i]; j < m and r[i]; j++) {
int mi = min(now, c[j]);
res[i][j] += mi;
now -= mi;
c[j] -= mi;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/08/PS/LeetCode/find-valid-matrix-given-row-and-column-sums/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.