Maximize distinct elements of Array by combining two elements or splitting an element
Last Updated :
13 Apr, 2023
Given an array arr[] of length N, the task is to maximize the number of distinct elements in the array by performing either of the following operations, any number of times:
- For an index i(0 ≤ i < N), replace arr[i] with a and b such that arr[i] = a + b.
- For two indices i (0 ≤ i < N) and n (0 ≤ n < N), Replace arr[n] with (arr[i] + arr[n]). Pop arr[i] from the array.
Examples:
Input: arr[] = {1, 4, 2, 8}, N = 4
Output: 5
Explanation: arr[3] can be split into [3, 5] to form arr [] = {1, 4, 2, 3, 5}.
There is no other way to split this into more elements.
Input: arr[] = {1, 1, 4, 3}, N = 4
Output: 3
Explanation: No operations can be performed to increase the number of distinct elements.
Approach: The problem can be based on the following observation:
Using the second operation, the entire arr[] can be reduced to 1 element, such that arr[0] = sum(arr[]). Now, the array sum can be partitioned into maximum number of unique parts get maximum unique elements.
Follow the below steps to implement the observation:
- Iterate over the array and find the sum of array elements (say sum).
- Now to get the maximum unique partitions of sum, it is optimal to assign as low a value as possible to each part.
- So, loop from i = 1 as long as sum > 0:
- Subtract i from sum and then increment i by 1.
- The total number of unique elements is i - 1, as there is an extra incrementation at the last iteration of the loop.
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the maximum possible
// number of unique elements
int maxUniqueElems(int* Arr, int L)
{
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = 1;
// Looping till sums becomes 0
while (sums > 0) {
// Subtracting i from sums and
// incrementing i
sums -= i;
i++;
}
// Returning the result
return i - 1;
}
// Driver code
int main()
{
int arr[] = { 1, 4, 2, 8 };
int N = 4;
// Function call
cout << maxUniqueElems(arr, N);
return 0;
}
Java
// JAVA code to implement the above approach
import java.util.*;
class GFG
{
// Function to calculate the maximum possible
// number of unique elements
public static int maxUniqueElems(int []Arr, int L)
{
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = 1;
// Looping till sums becomes 0
while (sums > 0) {
// Subtracting i from sums and
// incrementing i
sums -= i;
i++;
}
// Returning the result
return i - 1;
}
// Driver code
public static void main(String []args)
{
int arr[] = new int[]{ 1, 4, 2, 8 };
int N = 4;
// Function call
System.out.println(maxUniqueElems(arr, N));
}
}
// This code is contributed by Taranpreet
Python3
# python3 code to implement the above approach
# Function to calculate the maximum possible
# number of unique elements
def maxUniqueElems(Arr, L):
# Initializing sums variable
sums = 0
# Calculating sum of array
for j in range(0, L):
sums += Arr[j]
# Initializing i to count total number of
# distinct elements
i = 1
# Looping till sums becomes 0
while (sums > 0):
# Subtracting i from sums and
# incrementing i
sums -= i
i += 1
# Returning the result
return i - 1
# Driver code
if __name__ == "__main__":
arr = [1, 4, 2, 8]
N = 4
# Function call
print(maxUniqueElems(arr, N))
# This code is contributed by rakeshsahni
JavaScript
<script>
// JavaScript code to implement the above approach
// Function to calculate the maximum possible
// number of unique elements
function maxUniqueElems(Arr, L){
// Initializing sums variable
let sums = 0
// Calculating sum of array
for(let j = 0; j < L; j++)
sums += Arr[j]
// Initializing i to count total number of
// distinct elements
let i = 1
// Looping till sums becomes 0
while (sums > 0){
// Subtracting i from sums and
// incrementing i
sums -= i
i += 1
}
// Returning the result
return i - 1
}
// Driver code
let arr = [1, 4, 2, 8]
let N = 4
// Function call
document.write(maxUniqueElems(arr, N),"</br>")
// This code is contributed by shinjanpatra
</script>
C#
// C# code to implement the above approach
using System;
class GFG {
// Function to calculate the maximum possible
// number of unique elements
static int maxUniqueElems(int[] Arr, int L)
{
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = 1;
// Looping till sums becomes 0
while (sums > 0) {
// Subtracting i from sums and
// incrementing i
sums -= i;
i++;
}
// Returning the result
return i - 1;
}
// Driver code
public static void Main()
{
int[] arr = { 1, 4, 2, 8 };
int N = 4;
// Function call
Console.WriteLine(maxUniqueElems(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
Time Complexity: O(max(N, sqrt(S))) where S is the sum of array
Auxiliary Space: O(1)
Another Approach:
- First, the necessary header file is included using the #include preprocessor directive. The bits/stdc++.h header file includes all standard library header files, making it easier to write code.
- The maxUniqueElems() function takes an integer array (Arr) and its length (L) as input arguments.
- The variable "sums" is initialized to 0.
- The for loop is used to calculate the sum of all elements of the input array. It iterates over each element of the array using the loop variable "j", and adds the value of the element to the "sums" variable.
- The next step is to calculate the total number of distinct elements in the input array. This is done using the formula: i = (sqrt(8*sums + 1) - 1) / 2 The formula is derived from the quadratic equation: n(n+1)/2 = sums, where n is the number of distinct elements. Solving the equation for n gives the above formula.
- Finally, the maxUniqueElems() function returns the value of "i".
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the maximum possible
// number of unique elements
int maxUniqueElems(int* Arr, int L)
{
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = (sqrt(8*sums + 1) - 1) / 2;
// Returning the result
return i;
}
// Driver code
int main()
{
int arr[] = { 1, 4, 2, 8 };
int N = 4;
// Function call
cout << maxUniqueElems(arr, N);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to calculate the maximum possible
// number of unique elements
static int maxUniqueElems(int[] Arr, int L) {
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = (int) ((Math.sqrt(8 * sums + 1) - 1) / 2);
// Returning the result
return i;
}
// Driver code
public static void main(String[] args) {
int[] arr = {1, 4, 2, 8};
int N = 4;
// Function call
System.out.println(maxUniqueElems(arr, N));
}
}
Python3
import math
# Function to calculate the maximum possible
# number of unique elements
def maxUniqueElems(Arr, L):
# Initializing sums variable
sums = 0
# Calculating sum of array
for j in range(L):
sums += Arr[j]
# Initializing i to count total number of
# distinct elements
i = (int(math.sqrt(8*sums + 1)) - 1) // 2
# Returning the result
return i
# Driver code
if __name__ == '__main__':
arr = [1, 4, 2, 8]
N = 4
# Function call
print(maxUniqueElems(arr, N))
C#
using System;
public class GFG {
// Function to calculate the maximum possible
// number of unique elements
static int maxUniqueElems(int[] Arr, int L) {
// Initializing sums variable
int sums = 0;
// Calculating sum of array
for (int j = 0; j < L; j++)
sums += Arr[j];
// Initializing i to count total number of
// distinct elements
int i = (int) ((Math.Sqrt(8 * sums + 1) - 1) / 2);
// Returning the result
return i;
}
// Driver code
public static void Main() {
int[] arr = {1, 4, 2, 8};
int N = 4;
// Function call
Console.Write(maxUniqueElems(arr, N));
}
}
JavaScript
function maxUniqueElems(arr) {
// Initializing sums variable
let sums = 0;
// Calculating sum of array
for (let j = 0; j < arr.length; j++) {
sums += arr[j];
}
// Initializing i to count total number of distinct elements
let i = Math.floor((Math.sqrt(8 * sums + 1) - 1) / 2);
// Returning the result
return i;
}
// Driver code
const arr = [1, 4, 2, 8];
console.log(maxUniqueElems(arr)); // Output: 3
- In the main() function, an integer array arr[] is declared and initialized with some values.
- The length of the array is stored in the integer variable N.
- The maxUniqueElems() function is called with the array arr[] and its length N as input arguments.
- The output of the maxUniqueElems() function is printed to the console using the cout statement.
- The program ends with a return 0 statement.
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read