给定两个整数和
, 在哪里
。找出一个人的最大人数
二进制矩阵可以具有每个大小的子矩阵
至少有一个像元为零。
例子:
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
方法可以使用贪婪方法解决问题。在第一个正方形子矩阵的右下角放置一个零,即坐标为(1,1)和(x,x)的子矩阵,并对称地创建其余矩阵,我们可以得到最小值零个数,或者最大个数。因此,通过观察,可以得出一个共同的结论,即存在零的数目(以最小排列方式)。可用单元总数为
在NxN矩阵中。
下面是上述方法的实现:
C++
// C++ program to get Maximum Number of
// ones in a matrix with given constraints
#include
using namespace std;
// Function that returns the maximum
// number of ones
int getMaxOnes(int n, int x)
{
// Minimum number of zeroes
int zeroes = (n / x);
zeroes = zeroes * zeroes;
// Totol cells = square of the size of the matrices
int total = n * n;
// Intialising the answer
int ans = total - zeroes;
return ans;
}
// Driver code
int main()
{
// Intitalising the variables
int n = 5;
int x = 2;
cout << getMaxOnes(n, x);
return 0;
}
Java
// Java program to get Maximum
// Number of ones in a matrix
// with given constraints
import java.io.*;
class GFG
{
// Function that returns
// the maximum number of ones
static int getMaxOnes(int n,
int x)
{
// Minimum number of zeroes
int zeroes = (n / x);
zeroes = zeroes * zeroes;
// Totol cells = square of
// the size of the matrices
int total = n * n;
// Intialising the answer
int ans = total - zeroes;
return ans;
}
// Driver code
public static void main (String[] args)
{
// Intitalising the variables
int n = 5;
int x = 2;
System.out.println(getMaxOnes(n, x));
}
}
// This code is contributed
// by akt_mit
Python3
# Python3 program to get
# Maximum Number of ones
# in a matrix with given
# constraints
# Function that returns
# the maximum number of ones
def getMaxOnes(n, x):
# Minimum number
# of zeroes
zeroes = (int)(n / x);
zeroes = zeroes * zeroes;
# Totol cells = square of
# the size of the matrices
total = n * n;
# Intialising
# the answer
ans = total - zeroes;
return ans;
# Driver code
# Intitalising the variables
n = 5;
x = 2;
print(getMaxOnes(n, x));
# This code is contributed
# by mits
C#
// C# program to get Maximum
// Number of ones in a matrix
// with given constraints
using System;
class GFG
{
// Function that returns
// the maximum number of ones
static int getMaxOnes(int n,
int x)
{
// Minimum number of zeroes
int zeroes = (n / x);
zeroes = zeroes * zeroes;
// Totol cells = square of
// the size of the matrices
int total = n * n;
// Intialising the answer
int ans = total - zeroes;
return ans;
}
// Driver code
static public void Main ()
{
// Intitalising the
// variables
int n = 5;
int x = 2;
Console.WriteLine(getMaxOnes(n, x));
}
}
// This code is contributed
// by ajit
PHP
输出:
21
时间复杂度: O(1)
辅助空间: O(1)