Suma máxima posible para una subsecuencia tal que no aparecen dos elementos a una distancia < K en la array

Dada una array arr[] de n enteros y un entero k , la tarea es encontrar la suma máxima posible para una subsecuencia tal que no aparezcan dos elementos de la subsecuencia a una distancia ≤ k en la array original.
Ejemplos: 
 

Entrada: arr[] = {5, 3, 4, 11, 2}, k=1 
Salida: 16 
Todas las subsecuencias posibles son {5, 4, 2}, {5, 11}, {5, 2}, {3, 11}, {3, 2}, {4, 2} y {11} 
de los cuales 5 + 11 = 16 da la suma máxima.
Entrada: arr[] = {6, 7, 1, 3, 8, 2, 4}, k = 2 
Salida: 15 
 

Enfoque: al elegir un elemento en el índice i , tenemos dos opciones, incluimos el elemento actual en la subsecuencia o no lo hacemos. Deje que dp[i] represente la suma máxima hasta ahora al alcanzar el elemento en el índice i . Podemos calcular el valor de dp[i] de la siguiente manera: 
 

dp[i] = max(dp[i – (k + 1)] + arr[i], dp[i – 1])
dp[i – (k + 1)] + arr[i] es el caso cuando el elemento en el índice i está incluido. En esa situación, el valor máximo será arr[i] + valor máximo hasta el último elemento incluido de la array. 
dp[i – 1] es el caso cuando el elemento actual no está incluido y el valor máximo hasta ahora será el valor máximo hasta el elemento anterior. 
 

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 maximum sum possible
int maxSum(int* arr, int k, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return arr[0];
    if (n == 2)
        return max(arr[0], arr[1]);
 
    // dp[i] represent the maximum sum so far
    // after reaching current position i
    int dp[n];
 
    // Initialize dp[0]
    dp[0] = arr[0];
 
    // Initialize the dp values till k since any
    // two elements included in the sub-sequence
    // must be atleast k indices apart, and thus
    // first element and second element
    // will be k indices apart
    for (int i = 1; i <= k; i++)
        dp[i] = max(arr[i], dp[i - 1]);
 
    // Fill remaining positions
    for (int i = k + 1; i < n; i++)
        dp[i] = max(arr[i], dp[i - (k + 1)] + arr[i]);
 
    // Return the maximum sum
    int max = *(std::max_element(dp, dp + n));
    return max;
}
 
// Driver code
int main()
{
    int arr[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    cout << maxSum(arr, k, n);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
     
// Function to return the maximum sum possible
static int maxSum(int []arr, int k, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return arr[0];
    if (n == 2)
        return Math.max(arr[0], arr[1]);
 
    // dp[i] represent the maximum sum so far
    // after reaching current position i
    int[] dp = new int[n];
 
    // Initialize dp[0]
    dp[0] = arr[0];
 
    // Initialize the dp values till k since any
    // two elements included in the sub-sequence
    // must be atleast k indices apart, and thus
    // first element and second element
    // will be k indices apart
    for (int i = 1; i <= k; i++)
        dp[i] = Math.max(arr[i], dp[i - 1]);
 
    // Fill remaining positions
    for (int i = k + 1; i < n; i++)
        dp[i] = Math.max(arr[i], dp[i - (k + 1)] + arr[i]);
 
    // Return the maximum sum
    return maximum(dp);
}
 
static int maximum(int[] arr)
{
    int max = Integer.MIN_VALUE;
    for(int i = 0; i < arr.length; i++)
    {
        if(arr[i] > max)
        {
            max = arr[i];
        }
    }
    return max;
}
 
// Driver code
public static void main (String[] args)
{
    int []arr = { 6, 7, 1, 3, 8, 2, 4 };
    int n = arr.length;
    int k = 2;
    System.out.println(maxSum(arr, k, n));
}
}
 
// This code is contributed by mits

Python3

# Python3 implementation of the approach
 
# Function to return the
# maximum sum possible
def maxSum(arr, k, n) :
     
    if (n == 0) :
        return 0;
    if (n == 1) :
        return arr[0];
    if (n == 2) :
        return max(arr[0], arr[1]);
 
    # dp[i] represent the maximum sum so far
    # after reaching current position i
    dp = [0] * n ;
 
    # Initialize dp[0]
    dp[0] = arr[0];
 
    # Initialize the dp values till k since any
    # two elements included in the sub-sequence
    # must be atleast k indices apart, and thus
    # first element and second element
    # will be k indices apart
    for i in range(1, k + 1) :
        dp[i] = max(arr[i], dp[i - 1]);
 
    # Fill remaining positions
    for i in range(k + 1, n) :
        dp[i] = max(arr[i],
                    dp[i - (k + 1)] + arr[i]);
 
    # Return the maximum sum
    max_element = max(dp);
    return max_element;
 
# Driver code
if __name__ == "__main__" :
    arr = [ 6, 7, 1, 3, 8, 2, 4 ];
    n = len(arr);
    k = 2;
     
    print(maxSum(arr, k, n));
     
# This code is contributed by Ryuga

C#

// C# implementation of the approach
using System;
using System.Linq;
 
class GFG
{
     
// Function to return the maximum sum possible
static int maxSum(int []arr, int k, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return arr[0];
    if (n == 2)
        return Math.Max(arr[0], arr[1]);
 
    // dp[i] represent the maximum sum so far
    // after reaching current position i
    int[] dp = new int[n];
 
    // Initialize dp[0]
    dp[0] = arr[0];
 
    // Initialize the dp values till k since any
    // two elements included in the sub-sequence
    // must be atleast k indices apart, and thus
    // first element and second element
    // will be k indices apart
    for (int i = 1; i <= k; i++)
        dp[i] = Math.Max(arr[i], dp[i - 1]);
 
    // Fill remaining positions
    for (int i = k + 1; i < n; i++)
        dp[i] = Math.Max(arr[i], dp[i - (k + 1)] + arr[i]);
 
    // Return the maximum sum
    int max = dp.Max();
    return max;
}
 
// Driver code
static void Main()
{
    int []arr = { 6, 7, 1, 3, 8, 2, 4 };
    int n = arr.Length;
    int k = 2;
    Console.WriteLine(maxSum(arr, k, n));
}
}
 
// This code is contributed by mits

Javascript

<script>
 
    // JavaScript implementation of the approach
     
    // Function to return the maximum sum possible
    function maxSum(arr, k, n)
    {
        if (n == 0)
            return 0;
        if (n == 1)
            return arr[0];
        if (n == 2)
            return Math.max(arr[0], arr[1]);
 
        // dp[i] represent the maximum sum so far
        // after reaching current position i
        let dp = new Array(n);
 
        // Initialize dp[0]
        dp[0] = arr[0];
 
        // Initialize the dp values till k since any
        // two elements included in the sub-sequence
        // must be atleast k indices apart, and thus
        // first element and second element
        // will be k indices apart
        for (let i = 1; i <= k; i++)
            dp[i] = Math.max(arr[i], dp[i - 1]);
 
        // Fill remaining positions
        for (let i = k + 1; i < n; i++)
            dp[i] = Math.max(arr[i], dp[i - (k + 1)] + arr[i]);
 
        // Return the maximum sum
        let max = Number.MIN_VALUE;
        for(let i = 0; i < dp.length; i++)
        {
            max = Math.max(max, dp[i]);
        }
        return max;
    }
     
    let arr = [ 6, 7, 1, 3, 8, 2, 4 ];
    let n = arr.length;
    let k = 2;
    document.write(maxSum(arr, k, n));
 
</script>
Producción: 

15

 

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

Publicación traducida automáticamente

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