Maximum number of ones in a N*N matrix with given constraints
Last Updated :
26 Aug, 2022
Given two integers and , where . Find the maximum number of one’s in a binary matrix can have such that every sub-matrix of size has atleast one cell as zero.
Examples:
Input:5 3
Output: Maximum number of ones = 24
The matrix will be:
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
Input:5 2
Output: Maximum number of ones = 21
The matrix will be:
1 1 1 1 1
1 0 1 0 1
1 1 1 1 1
1 0 1 0 1
1 1 1 1 1
Approach The problem can be solved using a greedy approach. Place a zero at the right-bottom corner of the first square sub-matrix, i.e. the sub-matrix with coordinates (1, 1) and (x, x), and create the rest of the matrix symmetrically, we can get the minimum number of zeros, or, the maximum number of ones. Thus by observing, a common conclusion can be drawn that there are number of zeroes, in the minimum arrangement. The total number of cells available is in a NxN matrix.
.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMaxOnes( int n, int x)
{
int zeroes = (n / x);
zeroes = zeroes * zeroes;
int total = n * n;
int ans = total - zeroes;
return ans;
}
int main()
{
int n = 5;
int x = 2;
cout << getMaxOnes(n, x);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getMaxOnes( int n,
int x)
{
int zeroes = (n / x);
zeroes = zeroes * zeroes;
int total = n * n;
int ans = total - zeroes;
return ans;
}
public static void main (String[] args)
{
int n = 5 ;
int x = 2 ;
System.out.println(getMaxOnes(n, x));
}
}
|
Python3
def getMaxOnes(n, x):
zeroes = ( int )(n / x);
zeroes = zeroes * zeroes;
total = n * n;
ans = total - zeroes;
return ans;
n = 5 ;
x = 2 ;
print (getMaxOnes(n, x));
|
C#
using System;
class GFG
{
static int getMaxOnes( int n,
int x)
{
int zeroes = (n / x);
zeroes = zeroes * zeroes;
int total = n * n;
int ans = total - zeroes;
return ans;
}
static public void Main ()
{
int n = 5;
int x = 2;
Console.WriteLine(getMaxOnes(n, x));
}
}
|
PHP
<?php
function getMaxOnes( $n , $x )
{
$zeroes = (int)( $n / $x );
$zeroes = $zeroes *
$zeroes ;
$total = $n * $n ;
$ans = $total - $zeroes ;
return $ans ;
}
$n = 5;
$x = 2;
echo getMaxOnes( $n , $x );
?>
|
Javascript
<script>
function getMaxOnes(n, x)
{
let zeroes = parseInt(n / x, 10);
zeroes = zeroes * zeroes;
let total = n * n;
let ans = total - zeroes;
return ans;
}
let n = 5;
let x = 2;
document.write(getMaxOnes(n, x));
</script>
|
Complexity Analysis:
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...