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.
1public class Solution {
2 public int[][] RestoreMatrix(int[] rowSum, int[] colSum) {
3 int m = rowSum.Length;
4 int n = colSum.Length;
5 int[][] matrix = new int[m][];
6 for (int i = 0; i < m; i++) {
7 matrix[i] = new int[n];
8 }
9 int r = 0, c = 0;
10 while (r < m && c < n) {
11 int fill = Math.Min(rowSum[r], colSum[c]);
12 matrix[r][c] = fill;
13 rowSum[r] -= fill;
14 colSum[c] -= fill;
15 if (rowSum[r] == 0) r++;
16 if (colSum[c] == 0) c++;
17 }
18 return matrix;
19 }
20}
The C# solution uses a straightforward loop over the row and column indices, reducing sums directly. For each matrix element matrix[r][c], the minimal current row or column sum is chosen, updating results in a systematic way through the given indices.