Número de subsecuencias de longitud K con suma mínima

Dada una array arr[] de tamaño N y un número entero K , la tarea es encontrar el número de subsecuencias de longitud K de esta array tal que la suma de estas subsecuencias sea la mínima posible.

Ejemplos: 

Entrada: arr[] = {1, 2, 3, 4}, K = 2 
Salida:
Las subsecuencias de longitud 2 son (1, 2), (1, 3), (1, 4), 
(2, 3) , (2, 4) y (3, 4). 
La suma mínima es 3 y la única subsecuencia 
con esta suma es (1, 2).

Entrada: arr[] = {2, 1, 2, 2, 2, 1}, K = 3 
Salida: 4  

Enfoque: La suma mínima posible de una subsecuencia de longitud K de la array dada es la suma de los K elementos más pequeños de la array. Sea X el elemento máximo entre los K elementos más pequeños del arreglo, y sea el número de veces que ocurre entre los K, los elementos más pequeños del arreglo, Y , y, su ocurrencia total, en el arreglo completo, sea cntX . Ahora, hay cntX C Y formas de seleccionar este elemento, en los K elementos más pequeños, que es el conteo de subsecuencias requeridas.

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 value of
// Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int C[n + 1][k + 1];
    int i, j;
 
    // Calculate value of Binomial Coefficient
    // in bottom up manner
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= min(i, k); j++) {
 
            // Base Cases
            if (j == 0 || j == i)
                C[i][j] = 1;
 
            // Calculate value using previously
            // stored values
            else
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
        }
    }
 
    return C[n][k];
}
 
// Function to return the count
// of valid subsequences
int cntSubSeq(int arr[], int n, int k)
{
 
    // Sort the array
    sort(arr, arr + n);
 
    // Maximum among the minimum K elements
    int num = arr[k - 1];
 
    // Y will store the frequency of num
    // in the minimum K elements
    int Y = 0;
    for (int i = k - 1; i >= 0; i--) {
        if (arr[i] == num)
            Y++;
    }
 
    // cntX will store the frequency of
    // num in the complete array
    int cntX = Y;
    for (int i = k; i < n; i++) {
        if (arr[i] == num)
            cntX++;
    }
 
    return binomialCoeff(cntX, Y);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(int);
    int k = 2;
 
    cout << cntSubSeq(arr, n, k);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
     
    // Function to return the value of
    // Binomial Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int C[][] = new int [n + 1][k + 1];
        int i, j;
     
        // Calculate value of Binomial Coefficient
        // in bottom up manner
        for (i = 0; i <= n; i++)
        {
            for (j = 0; j <= Math.min(i, k); j++)
            {
     
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;
     
                // Calculate value using previously
                // stored values
                else
                    C[i][j] = C[i - 1][j - 1] +
                              C[i - 1][j];
            }
        }
        return C[n][k];
    }
     
    // Function to return the count
    // of valid subsequences
    static int cntSubSeq(int arr[], int n, int k)
    {
     
        // Sort the array
        Arrays.sort(arr);
     
        // Maximum among the minimum K elements
        int num = arr[k - 1];
     
        // Y will store the frequency of num
        // in the minimum K elements
        int Y = 0;
        for (int i = k - 1; i >= 0; i--)
        {
            if (arr[i] == num)
                Y++;
        }
     
        // cntX will store the frequency of
        // num in the complete array
        int cntX = Y;
        for (int i = k; i < n; i++)
        {
            if (arr[i] == num)
                cntX++;
        }
        return binomialCoeff(cntX, Y);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 1, 2, 3, 4 };
        int n = arr.length;
        int k = 2;
     
        System.out.println(cntSubSeq(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
     
class GFG
{
     
    // Function to return the value of
    // Binomial Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int [,]C = new int [n + 1, k + 1];
        int i, j;
     
        // Calculate value of Binomial Coefficient
        // in bottom up manner
        for (i = 0; i <= n; i++)
        {
            for (j = 0; j <= Math.Min(i, k); j++)
            {
     
                // Base Cases
                if (j == 0 || j == i)
                    C[i, j] = 1;
     
                // Calculate value using previously
                // stored values
                else
                    C[i, j] = C[i - 1, j - 1] +
                              C[i - 1, j];
            }
        }
        return C[n, k];
    }
     
    // Function to return the count
    // of valid subsequences
    static int cntSubSeq(int []arr, int n, int k)
    {
     
        // Sort the array
        Array.Sort(arr);
     
        // Maximum among the minimum K elements
        int num = arr[k - 1];
     
        // Y will store the frequency of num
        // in the minimum K elements
        int Y = 0;
        for (int i = k - 1; i >= 0; i--)
        {
            if (arr[i] == num)
                Y++;
        }
     
        // cntX will store the frequency of
        // num in the complete array
        int cntX = Y;
        for (int i = k; i < n; i++)
        {
            if (arr[i] == num)
                cntX++;
        }
        return binomialCoeff(cntX, Y);
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int []arr = { 1, 2, 3, 4 };
        int n = arr.Length;
        int k = 2;
     
        Console.WriteLine(cntSubSeq(arr, n, k));
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
 
# Function to return the value of
# Binomial Coefficient C(n, k)
def binomialCoeff(n, k) :
 
    C = [[0 for i in range(n + 1)]
               for j in range(k + 1)]
 
    # Calculate value of Binomial Coefficient
    # in bottom up manner
    for i in range (0, n + 1 ):
        for j in range (0, min(i, k) + 1):
 
            # Base Cases
            if (j == 0 or j == i):
                C[i][j] = 1
 
            # Calculate value using previously
            # stored values
            else :
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
         
    return C[n][k]
 
# Function to return the count
# of valid subsequences
def cntSubSeq(arr, n, k) :
 
    # Sort the array
    arr.sort()
 
    # Maximum among the minimum K elements
    num = arr[k - 1];
 
    # Y will store the frequency of num
    # in the minimum K elements
    Y = 0;
    for i in range (k - 1, -1, 1) :
        if (arr[i] == num):
            Y += 1
 
    # cntX will store the frequency of
    # num in the complete array
    cntX = Y;
    for i in range (k, n):
        if (arr[i] == num) :
            cntX += 1
     
    return binomialCoeff(cntX, Y)
 
# Driver code
arr = [ 1, 2, 3, 4 ]
n = len(arr)
k = 2
print(cntSubSeq(arr, n, k))
 
# This code is contributed by ihritik

Javascript

<script>
// Javascript implementation of the
// above approach
 
// Function for the binomial coefficient
function binomialCoeff(n, k)
{
 
    var C = new Array(n + 1);
    // Loop to create 2D array using 1D array
    for (var i = 0; i < C.length; i++) {
        C[i] = new Array(k + 1);
    }
    var i, j;
   
    // Calculate value of Binomial Coefficient
    // in bottom up manner
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= Math.min(i, k); j++) {
            // Base Cases
            if (j == 0 || j == i)
                C[i][j] = 1;
   
            // Calculate value using previously
            // stored values
            else
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
        }
    }
   
    return C[n][k];
}
   
// Function to return the count
// of valid subsequences
function cntSubSeq(arr, n, k)
{
   
    // Sort the array
    arr.sort();
   
    // Maximum among the minimum K elements
    var num = arr[k - 1];
   
    // Y will store the frequency of num
    // in the minimum K elements
    var Y = 0;
    for (var i = k - 1; i >= 0; i--) {
        if (arr[i] == num)
            Y+=1;
    }
   
    // cntX will store the frequency of
    // num in the complete array
    var cntX = Y;
    for (var i = k; i < n; i++) {
        if (arr[i] == num)
            cntX+=1;
    }
   
    return binomialCoeff(cntX, Y);
}
 
// Driver code
var arr = [ 1, 2, 3, 4 ];
var n = arr.length;
var k = 2;
document.write(cntSubSeq(arr, n, k));
 
// This code is contributed by ShubhamSingh10
</script>
Producción: 

1

 

Complejidad temporal: o(n 2 )

Espacio Auxiliar: O(n * k)

Publicación traducida automáticamente

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