Tiempo máximo posible que se puede formar a partir de cuatro dígitos

Dada una array arr[] que tiene solo 4 dígitos enteros. La tarea es devolver el tiempo máximo de 24 horas que se puede formar utilizando los dígitos de la array. 
Tenga en cuenta que el tiempo mínimo en formato de 24 horas es 00:00 y el máximo es 23:59 . Si no se puede formar una hora válida, devuelva -1 .
Ejemplos: 
 

Entrada: arr[] = {1, 2, 3, 4} 
Salida: 23:41
Entrada: arr[] = {5, 5, 6, 6} 
Salida: -1 
 

Enfoque: Cree un HashMap y almacene la frecuencia de cada dígito en el mapa que se puede usar para saber cuántos de esos dígitos están disponibles. 
Ahora, para generar un tiempo válido, se deben cumplir las siguientes condiciones: 
 

  • El primer dígito de las horas debe ser del rango [0, 2] . Comience a verificar en orden decreciente para maximizar el tiempo, es decir, de 2 a 0 . Una vez elegido el dígito, disminuya su aparición en el mapa en 1 .
  • El segundo dígito de las horas debe ser del rango [0, 3] si el primer dígito se eligió como 2 , de lo contrario [0, 9] . Actualice HashMap en consecuencia después de elegir el dígito.
  • El primer dígito de los minutos debe ser del rango [0, 5] y el segundo dígito de los minutos debe ser del rango [0, 9] .

Si alguna de las condiciones anteriores falla, es decir, no se puede elegir ningún dígito en ningún momento, imprima -1 ; de lo contrario, imprima la hora.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the updated frequency map
// for the array passed as argument
map<int, int> getFrequencyMap(int arr[], int n)
{
    map<int, int> hashMap;
    for (int i = 0; i < n; i++) {
 
        hashMap[arr[i]]++;
    }
    return hashMap;
}
 
// Function that returns true if the passed digit is present
// in the map after decrementing it's frequency by 1
bool hasDigit(map<int, int>* hashMap, int digit)
{
 
    // If map contains the digit
    if ((*hashMap)[digit]) {
 
        // Decrement the frequency of the digit by 1
        (*hashMap)[digit]--;
 
        // True here indicates that the digit was found in the map
        return true;
    }
 
    // Digit not found
    return false;
}
 
// Function to return the maximum possible time_value in 24-Hours format
string getMaxtime_value(int arr[], int n)
{
    map<int, int> hashMap = getFrequencyMap(arr, n);
    int i;
    bool flag;
    string time_value = "";
 
    flag = false;
 
    // First digit of hours can be from the range [0, 2]
    for (i = 2; i >= 0; i--) {
        if (hasDigit(&hashMap, i)) {
            flag = true;
            time_value += (char)i + 48;
            break;
        }
    }
 
    // If no valid digit found
    if (!flag)
        return "-1";
 
    flag = false;
 
    // If first digit of hours was chosen as 2 then
    // the second digit of hours can be
    // from the range [0, 3]
    if (time_value[0] == '2') {
        for (i = 3; i >= 0; i--) {
            if (hasDigit(&hashMap, i)) {
                flag = true;
                time_value += (char)i + 48;
                break;
            }
        }
    }
 
    // Else it can be from the range [0, 9]
    else {
        for (i = 9; i >= 0; i--) {
            if (hasDigit(&hashMap, i)) {
                flag = true;
                time_value += (char)i + 48;
                break;
            }
        }
    }
    if (!flag)
        return "-1";
 
    // Hours and minutes separator
    time_value += ":";
 
    flag = false;
 
    // First digit of minutes can be from the range [0, 5]
    for (i = 5; i >= 0; i--) {
        if (hasDigit(&hashMap, i)) {
            flag = true;
            time_value += (char)i + 48;
            break;
        }
    }
    if (!flag)
        return "-1";
 
    flag = false;
 
    // Second digit of minutes can be from the range [0, 9]
    for (i = 9; i >= 0; i--) {
        if (hasDigit(&hashMap, i)) {
            flag = true;
            time_value += (char)i + 48;
            break;
        }
    }
    if (!flag)
        return "-1";
 
    // Return the maximum possible time_value
    return time_value;
}
 
// Driver code
int main()
{
    int arr[] = { 0, 0, 0, 9 };
    int n = sizeof(arr) / sizeof(int);
    cout << (getMaxtime_value(arr, n));
    return 0;
}
// contributed by Arnab Kundu

Java

// Java implementation of the approach
 
import java.util.*;
 
public class GFG {
 
    // Function to return the updated frequency map
    // for the array passed as argument
    static HashMap<Integer, Integer> getFrequencyMap(int arr[])
    {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            if (hashMap.containsKey(arr[i])) {
                hashMap.put(arr[i], hashMap.get(arr[i]) + 1);
            }
            else {
                hashMap.put(arr[i], 1);
            }
        }
        return hashMap;
    }
 
    // Function that returns true if the passed digit is present
    // in the map after decrementing it's frequency by 1
    static boolean hasDigit(HashMap<Integer, Integer> hashMap, int digit)
    {
 
        // If map contains the digit
        if (hashMap.containsKey(digit) && hashMap.get(digit) > 0) {
 
            // Decrement the frequency of the digit by 1
            hashMap.put(digit, hashMap.get(digit) - 1);
 
            // True here indicates that the digit was found in the map
            return true;
        }
 
        // Digit not found
        return false;
    }
 
    // Function to return the maximum possible time in 24-Hours format
    static String getMaxTime(int arr[])
    {
        HashMap<Integer, Integer> hashMap = getFrequencyMap(arr);
        int i;
        boolean flag;
        String time = "";
 
        flag = false;
 
        // First digit of hours can be from the range [0, 2]
        for (i = 2; i >= 0; i--) {
            if (hasDigit(hashMap, i)) {
                flag = true;
                time += i;
                break;
            }
        }
 
        // If no valid digit found
        if (!flag) {
            return "-1";
        }
 
        flag = false;
 
        // If first digit of hours was chosen as 2 then
        // the second digit of hours can be
        // from the range [0, 3]
        if (time.charAt(0) == '2') {
            for (i = 3; i >= 0; i--) {
                if (hasDigit(hashMap, i)) {
                    flag = true;
                    time += i;
                    break;
                }
            }
        }
 
        // Else it can be from the range [0, 9]
        else {
            for (i = 9; i >= 0; i--) {
                if (hasDigit(hashMap, i)) {
                    flag = true;
                    time += i;
                    break;
                }
            }
        }
        if (!flag) {
            return "-1";
        }
 
        // Hours and minutes separator
        time += ":";
 
        flag = false;
 
        // First digit of minutes can be from the range [0, 5]
        for (i = 5; i >= 0; i--) {
            if (hasDigit(hashMap, i)) {
                flag = true;
                time += i;
                break;
            }
        }
        if (!flag) {
            return "-1";
        }
 
        flag = false;
 
        // Second digit of minutes can be from the range [0, 9]
        for (i = 9; i >= 0; i--) {
            if (hasDigit(hashMap, i)) {
                flag = true;
                time += i;
                break;
            }
        }
        if (!flag) {
            return "-1";
        }
 
        // Return the maximum possible time
        return time;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 0, 0, 0, 9 };
        System.out.println(getMaxTime(arr));
    }
}

Python3

# Python3 implementation of the approach
from collections import defaultdict
 
# Function to return the updated frequency
# map for the array passed as argument
def getFrequencyMap(arr, n):
     
    hashMap = defaultdict(lambda:0)
    for i in range(n):
        hashMap[arr[i]] += 1
         
    return hashMap
     
# Function that returns true if the passed
# digit is present in the map after
# decrementing it's frequency by 1
def hasDigit(hashMap, digit):
     
    # If map contains the digit
    if hashMap[digit] > 0:
     
        # Decrement the frequency of
        # the digit by 1
        hashMap[digit] -= 1
     
        # True here indicates that the
        # digit was found in the map
        return True
     
    # Digit not found
    return False
     
# Function to return the maximum possible
# time_value in 24-Hours format
def getMaxtime_value(arr, n):
     
    hashMap = getFrequencyMap(arr, n)
    flag = False
    time_value = ""
     
    # First digit of hours can be
    # from the range [0, 2]
    for i in range(2, -1, -1):
        if hasDigit(hashMap, i) == True:
            flag = True
            time_value += str(i)
            break
     
    # If no valid digit found
    if not flag:
        return "-1"
     
    flag = False
     
    # If first digit of hours was chosen as 2 then
    # the second digit of hours can be
    # from the range [0, 3]
    if(time_value[0] == '2'):
        for i in range(3, -1, -1):
            if hasDigit(hashMap, i) == True:
                flag = True
                time_value += str(i)
                break
     
    # Else it can be from the range [0, 9]
    else:
        for i in range(9, -1, -1):
            if hasDigit(hashMap, i) == True:
                flag = True
                time_value += str(i)
                break
             
    if not flag:
        return "-1"
     
    # Hours and minutes separator
    time_value += ":"
     
    flag = False
     
    # First digit of minutes can be
    # from the range [0, 5]
    for i in range(5, -1, -1):
        if hasDigit(hashMap, i) == True:
            flag = True
            time_value += str(i)
            break
         
    if not flag:
        return "-1"
     
    flag = False
     
    # Second digit of minutes can be
    # from the range [0, 9]
    for i in range(9, -1, -1):
        if hasDigit(hashMap, i) == True:
            flag = True
            time_value += str(i)
            break
         
    if not flag:
        return "-1"
     
    # Return the maximum possible
    # time_value
    return time_value
     
# Driver code
if __name__ == "__main__":
     
    arr = [0, 0, 0, 9]
    n = len(arr)
    print(getMaxtime_value(arr, n))
     
# This code is contributed by
# Rituraj Jain

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to return the updated frequency map
    // for the array passed as argument
    static Dictionary<int, int> getFrequencyMap(int []arr)
    {
        Dictionary<int, int> hashMap = new Dictionary<int, int>();
        for (int i = 0; i < arr.Length; i++)
        {
            if (hashMap.ContainsKey(arr[i]))
            {
                hashMap[arr[i]] = hashMap[arr[i]] + 1;
            }
            else
            {
                hashMap.Add(arr[i], 1);
            }
        }
        return hashMap;
    }
 
    // Function that returns true if the passed digit is present
    // in the map after decrementing it's frequency by 1
    static bool hasDigit(Dictionary<int, int> hashMap, int digit)
    {
 
        // If map contains the digit
        if (hashMap.ContainsKey(digit) && hashMap[digit] > 0)
        {
 
            // Decrement the frequency of the digit by 1
            hashMap[digit] = hashMap[digit] - 1;
 
            // True here indicates that the
            // digit was found in the map
            return true;
        }
 
        // Digit not found
        return false;
    }
 
    // Function to return the maximum
    // possible time in 24-Hours format
    static String getMaxTime(int []arr)
    {
        Dictionary<int, int> hashMap = getFrequencyMap(arr);
        int i;
        bool flag;
        String time = "";
 
        flag = false;
 
        // First digit of hours can be from the range [0, 2]
        for (i = 2; i >= 0; i--)
        {
            if (hasDigit(hashMap, i))
            {
                flag = true;
                time += i;
                break;
            }
        }
 
        // If no valid digit found
        if (!flag)
        {
            return "-1";
        }
 
        flag = false;
 
        // If first digit of hours was chosen as 2 then
        // the second digit of hours can be
        // from the range [0, 3]
        if (time[0] == '2')
        {
            for (i = 3; i >= 0; i--)
            {
                if (hasDigit(hashMap, i))
                {
                    flag = true;
                    time += i;
                    break;
                }
            }
        }
 
        // Else it can be from the range [0, 9]
        else
        {
            for (i = 9; i >= 0; i--)
            {
                if (hasDigit(hashMap, i))
                {
                    flag = true;
                    time += i;
                    break;
                }
            }
        }
        if (!flag)
        {
            return "-1";
        }
 
        // Hours and minutes separator
        time += ":";
 
        flag = false;
 
        // First digit of minutes can be from the range [0, 5]
        for (i = 5; i >= 0; i--)
        {
            if (hasDigit(hashMap, i))
            {
                flag = true;
                time += i;
                break;
            }
        }
        if (!flag)
        {
            return "-1";
        }
 
        flag = false;
 
        // Second digit of minutes can be from the range [0, 9]
        for (i = 9; i >= 0; i--)
        {
            if (hasDigit(hashMap, i))
            {
                flag = true;
                time += i;
                break;
            }
        }
        if (!flag)
        {
            return "-1";
        }
 
        // Return the maximum possible time
        return time;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = { 0, 0, 0, 9 };
        Console.WriteLine(getMaxTime(arr));
    }
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
      // JavaScript implementation of the approach
       
      // Function to return the updated frequency map
      // for the array passed as argument
      function getFrequencyMap(arr) {
        var hashMap = {};
        for (var i = 0; i < arr.length; i++) {
          if (hashMap.hasOwnProperty(arr[i])) {
            hashMap[arr[i]] = hashMap[arr[i]] + 1;
          } else {
            hashMap[arr[i]] = 1;
          }
        }
        return hashMap;
      }
 
      // Function that returns true if the passed digit is present
      // in the map after decrementing it's frequency by 1
      function hasDigit(hashMap, digit) {
        // If map contains the digit
        if (hashMap.hasOwnProperty(digit) && hashMap[digit] > 0) {
          // Decrement the frequency of the digit by 1
          hashMap[digit] = hashMap[digit] - 1;
 
          // True here indicates that the
          // digit was found in the map
          return true;
        }
 
        // Digit not found
        return false;
      }
 
      // Function to return the maximum
      // possible time in 24-Hours format
      function getMaxTime(arr) {
        var hashMap = getFrequencyMap(arr);
        var i;
        var flag;
        var time = "";
 
        flag = false;
 
        // First digit of hours can be from the range [0, 2]
        for (i = 2; i >= 0; i--) {
          if (hasDigit(hashMap, i)) {
            flag = true;
            time += i;
            break;
          }
        }
 
        // If no valid digit found
        if (!flag) {
          return "-1";
        }
 
        flag = false;
 
        // If first digit of hours was chosen as 2 then
        // the second digit of hours can be
        // from the range [0, 3]
        if (time[0] === "2") {
          for (i = 3; i >= 0; i--) {
            if (hasDigit(hashMap, i)) {
              flag = true;
              time += i;
              break;
            }
          }
        }
 
        // Else it can be from the range [0, 9]
        else {
          for (i = 9; i >= 0; i--) {
            if (hasDigit(hashMap, i)) {
              flag = true;
              time += i;
              break;
            }
          }
        }
        if (!flag) {
          return "-1";
        }
 
        // Hours and minutes separator
        time += ":";
 
        flag = false;
 
        // First digit of minutes can be from the range [0, 5]
        for (i = 5; i >= 0; i--) {
          if (hasDigit(hashMap, i)) {
            flag = true;
            time += i;
            break;
          }
        }
        if (!flag) {
          return "-1";
        }
 
        flag = false;
 
        // Second digit of minutes can be from the range [0, 9]
        for (i = 9; i >= 0; i--) {
          if (hasDigit(hashMap, i)) {
            flag = true;
            time += i;
            break;
          }
        }
        if (!flag) {
          return "-1";
        }
 
        // Return the maximum possible time
        return time;
      }
 
      // Driver code
      var arr = [0, 0, 0, 9];
      document.write(getMaxTime(arr));
       
 </script>
Producción: 

09:00

 

Complejidad Temporal: O(n), ya que el ciclo va de 0 a (n – 1). 

Espacio Auxiliar: O(n), ya que se han tomado n espacios extra.

Publicación traducida automáticamente

Artículo escrito por Sanjit_Prasad 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 *