给定一个包含从1到N 的自然数的数组arr[] ,任务是找到在以下操作后可以相等的最大元素数:
- 从数组中删除任何一对元素并将它们的总和插入数组。
- 重复上述操作任意次数以最大化相等元素的计数。
例子:
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
Javascript
输出:
3
性能分析:
- 时间复杂度: O(1)
- 辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live