Sponsored
Sponsored
The greedy approach involves iterating over the matrix and at each cell (i, j), filling it with the minimum of the current rowSum[i] and colSum[j]. This method works because as we fill the matrix, we can always satisfy both the row and column conditions by subtracting the filled value from each.
Move through the matrix, adjusting row and column sums at each step. This continues until we've filled the entire matrix, ensuring the integrity of both row and column sum conditions.
Time Complexity: O(m + n), where m and n are the lengths of rowSum and colSum respectively, as we're adjusting values once per index.
Space Complexity: O(m * n) for storing the matrix.
1var restoreMatrix = function(rowSum, colSum) {
2 const m = rowSum.length;
3 const n = colSum.length;
4 const matrix = Array.from({ length: m }, () => Array(n).fill(0));
5 let i = 0, j = 0;
6 while (i < m && j < n) {
7 const fill = Math.min(rowSum[i], colSum[j]);
8 matrix[i][j] = fill;
9 rowSum[i] -= fill;
10 colSum[j] -= fill;
11 if (rowSum[i] === 0) i++;
12 if (colSum[j] === 0) j++;
13 }
14 return matrix;
15};
This JavaScript function constructs the required matrix using a while loop, filling each position with the minimal current corresponding row and column sums. Adjustments then determine the next indices to be evaluated, zeroing out to meet requirements effectively.