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 a 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.

Example:

Input:  rowSum=[3,8], colSum=[4,7]
Output: [[3,0],
[1,7]]

Approach

Java

import java.util.Arrays;

public class FindValidMatrix {
    public static void main(String[] args) {
        int rowSum[] = { 38 };
        int colSum[] = { 47 };
        int matrix[][] = restoreMatrix(rowSum, colSum);
        System.out.println(Arrays.deepToString(matrix));
    }

    static int[][] restoreMatrix(int[] rowSumint[] colSum) {
        int n = rowSum.length;
        int m = colSum.length;
        int res[][] = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int x = Math.min(rowSum[i], colSum[j]);
                res[i][j] = x;
                colSum[j] -= x;
                rowSum[i] -= x;
            }
        }
        return res;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> restoreMatrix(vector<int>& rowSum,
         vector<int>& colSum) {
        int n=rowSum.size(),m=colSum.size();
        vector<vector<int>> res(n,vector<int>(m));
          for(int i=0;i<n;i++)
          {
              for(int j=0;j<m;j++)
              {
                  int x=min(rowSum[i],colSum[j]);
                  res[i][j]=x;
                  colSum[j]-=x;
                  rowSum[i]-=x;
              }
          }
       return res;
 }
int main()
{
   vector<introwSum ={3,8};
   vector<intcolSum  ={4,7};
   vector<vector<int>> matrix=restoreMatrix(rowSum,colSum);
   cout<<"[";
   for(int i=0;i<matrix.size();i++)
      {
          cout<<"[";
          for(int j=0;j<matrix[i].size();j++)
            {
                if(j!=matrix[i].size()-1)
                   cout<<matrix[i][j]<<",";
                else
                 cout<<matrix[i][j];
            }
          cout<<"]";
          if(i!=matrix.size()-1)
          cout<<",\n";
      }
    cout<<"]";
    return 0;
}


No comments:

Post a Comment