Maximice el recuento de elementos de array únicos incrementando los elementos de array en K

Dada una array arr[] que consta de N enteros y un entero K, la tarea es encontrar el máximo número posible de elementos únicos aumentando cualquier elemento de la array en K solo una vez.

Ejemplos: 

Entrada: arr[] = {0, 2, 4, 3, 4}, K = 1
Salida: 5
Explicación:
Incrementar arr[2] ( = 4) por K ( = 1). Por lo tanto, la nueva array es {0, 2, 4, 3, 5} que tiene 5 elementos únicos.

Entrada: arr[] = {2, 3, 2, 4, 5, 5, 7, 4}, K = 2
Salida: 7
Explicación: 
Aumentar 4 en 2 = 6. 
Aumentar elemento 7 en 2 = 9
Aumentar 5 en 2 = 7. 
La nueva array es {2, 3, 2, 4, 5, 7, 9, 6} que contiene 7 elementos únicos.

Enfoque: la idea para resolver este problema es almacenar la frecuencia de los elementos de la array en un mapa y cambiar los elementos de la array en consecuencia para obtener elementos únicos en la array después de incrementar cualquier valor en K . Siga los pasos a continuación para resolver el problema:

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum unique
// elements in array after incrementing
// any element by K
void maxDifferent(int arr[], int N, int K)
{
    // Stores the count of element
    // in array
    map<int, int> M;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Increase the counter of
        // the array element by 1
        M[arr[i]]++;
    }
 
    // Traverse the map
    for (auto it = M.begin();
         it != M.end(); it++) {
 
        // Extract the current element
        int current_element = it->first;
 
        // Number of times the current
        // element is present in array
        int count = it->second;
 
        // If element is present only
        // once, then do not change it
        if (count == 1)
            continue;
 
        // If the count > 1 then change
        // one of the same current
        // elements to (current_element + K)
        // and increase its count by 1
        M[current_element + K]++;
    }
 
    // The size of the map is the
    // required answer
    cout << M.size();
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 2, 4, 5, 5, 7, 4 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxDifferent(arr, N, K);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to find the maximum unique
// elements in array after incrementing
// any element by K
static void maxDifferent(int arr[], int N, int K)
{
     
    // Stores the count of element
    // in array
    HashMap<Integer,
            Integer> M = new HashMap<Integer,
                                     Integer>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Increase the counter of
        // the array element by 1
        Integer count = M.get(arr[i]);
         
        if (count == null)
        {
            M.put(arr[i], 1);
        }
        else
        {
            M.put(arr[i], count + 1);
        }
    }
 
    // Iterator itr = M.entrySet().iterator();
    Iterator<Map.Entry<Integer,
                       Integer>> itr = M.entrySet().iterator();
 
    int[] ar1 = new int[N];
 
    // Traverse the map
    while (itr.hasNext())
    {
        Map.Entry<Integer, Integer> Element = itr.next();
 
        // Extract the current element
        int current_element = (int)Element.getKey();
 
        // Number of times the current
        // element is present in array
        int count = (int)Element.getValue();
 
        // If element is present only
        // once, then do not change it
        if (count == 1)
            continue;
 
        // If the count > 1 then change
        // one of the same current
        // elements to (current_element + K)
        // and increase its count by 1
        ar1[current_element + K]++;
    }
 
    for(int i = 0; i < N; i++)
    {
        if (ar1[i] >= 0)
        {
            Integer count = M.get(ar1[i]);
             
              if (count == null)
              {
                  M.put(ar1[i], 1);
            }
            else
            {
                M.put(ar1[i], count + 1);
            }
        }
    }
 
    // The size of the map is the
    // required answer
    System.out.println(M.size());
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 2, 4, 5, 5, 7, 4 };
    int K = 2;
    int N = arr.length;
     
    // Function Call
    maxDifferent(arr, N, K);
}
}
 
// This code is contributed by Dharanendra L V

Python3

# Python3 program for the above approach
 
# Function to find the maximum unique
# elements in array after incrementing
# any element by K
def maxDifferent(arr, N, K):
     
    # Stores the count of element
    # in array
    M = {}
 
    # Traverse the array
    for i in range(N):
 
        # Increase the counter of
        # the array element by 1
        M[arr[i]] = M.get(arr[i], 0) + 1
 
    # Traverse the map
    for it in list(M.keys()):
 
        # Extract the current element
        current_element = it
 
        # Number of times the current
        # element is present in array
        count = M[it]
 
        # If element is present only
        # once, then do not change it
        if (count == 1):
            continue
 
        # If the count > 1 then change
        # one of the same current
        # elements to (current_element + K)
        # and increase its count by 1
        M[current_element + K] = M.get(current_element, 0) + 1
 
    # The size of the map is the
    # required answer
    print(len(M))
 
# Driver Code
if __name__ == '__main__':
    arr=[2, 3, 2, 4, 5, 5, 7, 4]
    K = 2
    N = len(arr)
 
    # Function Call
    maxDifferent(arr, N, K)
 
    # This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
// Function to find the maximum unique
// elements in array after incrementing
// any element by K
static void maxDifferent(int []arr, int N, int K)
{
     
    // Stores the count of element
    // in array
    Dictionary<int,
            int> M = new Dictionary<int,
                                     int>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Increase the counter of
        // the array element by 1
        int count = M.ContainsKey(arr[i]) ? M[arr[i]] : 0;
         
        if (count == 0)
        {
            M.Add(arr[i], 1);
        }
        else
        {
            M[arr[i]] = count + 1;
        }
    }
 
    int[] ar1 = new int[N];
 
    // Traverse the map
    foreach(KeyValuePair<int, int> Element in M)
    {
 
        // Extract the current element
        int current_element = (int)Element.Key;
 
        // Number of times the current
        // element is present in array
        int count = (int)Element.Value;
 
        // If element is present only
        // once, then do not change it
        if (count == 1)
            continue;
 
        // If the count > 1 then change
        // one of the same current
        // elements to (current_element + K)
        // and increase its count by 1
        ar1[current_element + K]++;
    }
 
    for(int i = 0; i < N; i++)
    {
        if (ar1[i] >= 0)
        {
            int count = M.ContainsKey(ar1[i]) ? M[ar1[i]] : 0;           
              if (count == 0)
              {
                  M.Add(ar1[i], 1);
            }
            else
            {
                M[ar1[i]] = count + 1;
            }
        }
    }
 
    // The size of the map is the
    // required answer
    Console.WriteLine(M.Count);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 2, 3, 2, 4, 5, 5, 7, 4 };
    int K = 2;
    int N = arr.Length;
     
    // Function Call
    maxDifferent(arr, N, K);
}
}
 
// This code contributed by shikhasingrajput

Javascript

<script>
 
// JavaScript program for the above approach
 
// Function to find the maximum unique
// elements in array after incrementing
// any element by K
function maxDifferent(arr, N, K)
{
    // Stores the count of element
    // in array
    var M = new Map();
 
    // Traverse the array
    for (var i = 0; i < N; i++) {
 
        // Increase the counter of
        // the array element by 1
        if(M.has(arr[i]))
        {
            M.set(arr[i], M.get(arr[i])+1);
        }
        else
        {
            M.set(arr[i],1);
        }
    }
 
    M.forEach((value, key) => {
 
        // Extract the current element
        var current_element = key;
 
        // Number of times the current
        // element is present in array
        var count = value;
 
        // If element is present only
        // once, then do not change it
        if (count != 1)
        {
 
        // If the count > 1 then change
        // one of the same current
        // elements to (current_element + K)
        // and increase its count by 1
        if(M.has(current_element+K))
        {
            M.set(current_element+K,
            M.get(current_element+K)+1)
        }
        else
        {
            M.set(current_element+K,1);
        }
         
        }
    });
 
    // The size of the map is the
    // required answer
    document.write( M.size);
}
 
// Driver Code
var arr = [2, 3, 2, 4, 5, 5, 7, 4];
var K = 2;
var N = arr.length;
 
// Function Call
maxDifferent(arr, N, K);
 
</script>
Producción: 

7

 

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por adarsh_sinhg y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *