How to find the maximum possible number of ones that the matrix M can have in Python ?

  C & C ++ Interview Q&A
Dear readers, in today’s tutorial, learn how to find the maximum possible number near the matrix M in Python?
Dimension w x h with dimension M, such that each cell has a value of 0 or 1, and any square sub-matrix of M has the largest size of l x l. We have to find the maximum possible number of people that the matrix M can have.

So, if the input is like w = 3, h = 3, l = 2, maxOnes = 1, then output 4 will have a 3 * 3 matrix, no 2 * 2 sub-matrix can exceed 1.

#include <bits/stdc++.h>
using namespace std;
class program{
   public:
   int maximumNumberOfOnes(int width, int height, int n, int maxOnes) {
      int ret = 0;
      vector < vector <int> > sq(n, vector <int>(n));
      for(int i = 0; i < height; i++){
         for(int j = 0; j < width; j++){
            sq[i % n][j % n]++;
         }
      }
      vector <int> v;
      for(int i = 0; i < n; i++){
         for(int j = 0; j < n ; j++){
            v.push_back(sq[i][j]);
         }
      }
      sort(v.rbegin(), v.rend());
      for(int i = 0, j = 0; i < v.size() && j < maxOnes; i++, j++){
         ret += v[i];
      }
      return ret;
   }
};
main(){
   program ob;
   cout << (ob.maximumNumberOfOnes(3,3,2,1));
}

Output

4

LEAVE A COMMENT