- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Given the task is to find the maximum number of ones in a binary matrix possible with the following constraints.

Two integers N and X are given where X<=N. The size of the binary matrix should be N*N and every sub-matrix of size X*X should contain at least one zero.

Let’s now understand what we have to do using an example −

**Input** − N=4, X=2

**Output** − 12

**Explanation** − The resultant matrix will be −

1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1

**Input** − N=7, X=3

**Output** − 45

To obtain the maximum number of ones, first we will have to find the minimum number of zeros required in the given matrix.

By observing a common pattern in all the matrices, it can be seen that the number of zeroes required = (N / X)

^{2}So the maximum number of ones = Total elements in matrix – number of zeros\

In function MaxOne() create a variable Z of type int and store in it the minimum number of zeros required which is equal to (N / X)

^{2}Then initialize another variable total = N*N of type int to store the total size of the matrix.

Then finally initialize int ans = total – Z to store the final answer and return ans.

#include <bits/stdc++.h> using namespace std; int MaxOne(int N, int X){ // Minimum number of zeroes that are needed int Z = (N / X); Z = Z * Z; /* Totol elements in matrix = square of the size of the matrices*/ int total =N * N; //Final answer int ans = total - Z; return ans; } int main(){ int N = 4; int X = 2; cout << MaxOne(N, X); return 0; }

If we run the above code we will get the following output −

12

- Related Questions & Answers
- Maximum Number of Ones in C++
- Maximum GCD of N integers with given product in C++
- Maximum determinant of a matrix with every values either 0 or n in C++
- Maximum difference of zeros and ones in binary string - (O(n) time) in C++
- Maximum number of pieces in N cuts in C++
- Find the longest path in a matrix with given constraints in C++
- Matrix creation of n*n in Python
- Count digits in given number N which divide N in C++
- Maximum number of dots after throwing a dice N times in C++
- Primitive root of a prime number n modulo n in C++
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Area of a polygon with given n ordered vertices in C++
- How to print a matrix of size n*n in spiral order using C#?
- Find four factors of N with maximum product and sum equal to N in C++
- Convert a number m to n using minimum number of given operations in C++

Advertisements