Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum
Last Updated :
31 May, 2022
Given an array arr[] containing natural numbers from 1 to N, the task is to find the maximum number of elements that can be made equal after the below operations:
- Remove any pair of elements from the array and insert their sum to an array.
- Repeat the above operation any numbers of times to maximize the count of equal elements.
Examples:
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
Approach: The key observation in the problem is that:
- If N is even, we can make a maximum count of equal elements by
- If N is odd, we can make the maximum count of equal elements by
Therefore, the answer will always be
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countEqual( int n)
{
return (n + 1) / 2;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countEqual(n);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int countEqual( int n)
{
return (n + 1 ) / 2 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 };
int n = arr.length;
System.out.println(countEqual(n));
}
}
|
Python3
def countEqual(n):
return (n + 1 ) / / 2
lst = [ 1 , 2 , 3 , 4 , 5 , 6 ]
n = len (lst)
print (countEqual(n))
|
C#
using System;
class GFG{
static int countEqual( int n)
{
return (n + 1) / 2;
}
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6};
int n = arr.Length;
Console.WriteLine(countEqual(n));
}
}
|
Javascript
<script>
function countEqual(n)
{
return parseInt((n + 1) / 2);
}
var arr = [ 1, 2, 3, 4, 5, 6 ];
var n = arr.length;
document.write( countEqual(n));
</script>
|
Performance Analysis:
Time Complexity: O(1), as we are not using any loops or recursion.
Auxiliary Space: O(1), as we are not using any extra space.
Share your thoughts in the comments
Please Login to comment...