给定一个数组arr [],它包含从1到N的自然数,任务是找到在执行以下操作后可以相等的最大元素数:
- 从数组中删除任何一对元素,并将它们的总和插入到数组中。
- 重复上述操作任意次,以最大程度地增加相等元素的数量。
例子:
Input: arr[] = {1, 2, 3, 4}
Output: 2
Explanation:
We can perform following operations:
{1, 2, 3, 4} -> {3, 3, 4} -> 2 elements are equal
Input: arr[] = {1 2 3 4 5 6}
Output: 3
Explanation:
{1, 2, 3, 4, 5, 6} -> {7, 2, 3, 4, 5} -> {7, 7, 3, 4} -> {7, 7, 37} -> 3 elements are equal
方法:问题中的主要观察结果是:
- 如果N是偶数,我们可以使相等元素的最大数量为
- 如果N是奇数,我们可以使相等元素的最大数量为
因此,答案永远是
下面是上述方法的实现:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
// Function to count maximum number
// of array elements equal
int countEqual(int n)
{
return (n + 1) / 2;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
cout << countEqual(n);
return 0;
}
Java
// Java implementation of
// the above approach
import java.io.*;
class GFG{
// Function to count maximum number
// of array elements equal
static int countEqual(int n)
{
return (n + 1) / 2;
}
// Driver Code
public static void main (String[] args)
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = arr.length;
// Function call
System.out.println(countEqual(n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of
# the above approach
# Function to count maximum number
# of array elements equal
def countEqual(n):
return (n + 1) // 2
# Driver Code
lst = [ 1, 2, 3, 4, 5, 6 ]
n = len(lst)
# Function call
print(countEqual(n))
# This code is contributed by vishu2908
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function to count maximum number
// of array elements equal
static int countEqual(int n)
{
return (n + 1) / 2;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6};
int n = arr.Length;
// Function call
Console.WriteLine(countEqual(n));
}
}
// This code is contributed by Rajput-Ji
输出:
3
性能分析:
- 时间复杂度: O(1)
- 辅助空间: O(1)