Maximice la suma de elementos de array indexados impares seleccionando repetidamente como máximo 2*M elementos de array desde el principio

Dada una array arr[] que consta de N enteros y un entero M ( inicialmente 1 ), la tarea es encontrar la suma máxima de elementos de la array elegidos por el jugador A cuando dos jugadores A y B juegan de manera óptima de acuerdo con las siguientes reglas:

  • El jugador A comienza el juego.
  • En cada oportunidad, se puede elegir una cantidad X de elementos desde el comienzo de la array, donde X es inclusivo en el rango [1, 2 * M] elegido por el jugador respectivo en su turno.
  • Después de elegir los elementos de la array en los pasos anteriores, elimine esos elementos de la array y actualice el valor de M como el máximo de X y M .
  • El proceso anterior continuará hasta que se elijan todos los elementos de la array.

Ejemplos:

Entrada: arr[] = {2, 7, 9, 4, 4}
Salida: 10
Explicación:
Inicialmente, la array es arr[] = {2, 7, 9, 4, 4} y el valor de M = 1, a continuación son el orden de elección de los elementos de la array por parte de ambos jugadores:
Jugador A: El número de elementos se puede elegir entre el rango [1, 2*M], es decir, [1, 2]. Entonces, elija el elemento {2} y elimínelo. Ahora la array se modifica a {7, 9, 4, 4} y el valor de M es max(M, X) = max(1, 1) = 1(X es 1).
Jugador B: El número de elementos se puede elegir entre el rango [1, 2*M], es decir, [1, 2]. Entonces, elija el elemento {7, 9} y elimínelo. Ahora la array se modifica a {4, 4} y el valor de M es max(M, X) = max(1, 2) = 2(X es 2).
Jugador A:El número de elementos se puede elegir entre el rango [1, 2*2], es decir, [1, 1]. Entonces, elija el elemento {4, 4} y elimínelo. Ahora la array se vuelve vacía.

Por lo tanto, la suma de elementos elegida por el Jugador A es 2 + 4 + 4 = 10.

Entrada: arr[] = {1}
Salida: 1

 

Enfoque ingenuo: el enfoque más simple para resolver el problema dado es usar la recursividad y generar todas las combinaciones posibles de elegir elementos para ambos jugadores desde el principio de acuerdo con las reglas dadas e imprimir la suma máxima de elementos elegidos obtenidos para el jugador A. Siga los pasos a continuación para resolver el problema dado:

  • Declara una función recursiva , digamos recursiveChoosing(arr, start, M) que toma la array de parámetros, el índice inicial de la array actual y el valor inicial de M y realiza las siguientes operaciones en esta función:
    • Si el valor de inicio es mayor que N , devuelve 0 .
    • Si el valor de (N – inicio) es como máximo 2*M , devuelva la suma del elemento de la array desde el inicio del índice para la puntuación respectiva del jugador.
    • Inicialice un maxSum como 0 que almacene la suma máxima de elementos de array elegidos por el jugador A.
    • Encuentra la suma total de los elementos de la array desde el principio y guárdala en una variable, digamos total .
    • Iterar sobre el rango [1, 2*M] y realizar los siguientes pasos:
      • Para cada elemento X , elige X elementos desde el principio y llama recursivamente para elegir elementos de los elementos restantes (N – X) . Deje que el valor devuelto por esta llamada se almacene en maxSum .
      • Después de que finalice la llamada recursiva anterior, actualice el valor de maxSum al máximo de maxSum y (total – maxSum) .
    • Devuelve el valor de maxSum en cada llamada recursiva.
  • Después de completar los pasos anteriores, imprima el valor devuelto por la función recursiveChoosing(arr, 0, 1) .

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;
 
// Sum of all numbers in the array
// after start index
int sum(int arr[], int start, int N)
{
    int sum1 = 0;
    for(int i = start; i < N; i++)
    {
        sum1 += arr[i];
    }
    return sum1;
}
 
// Function to find the maximum sum of
// array elements chosen by Player A
// according to the given criteria
int recursiveChoosing(int arr[], int start,
                      int M, int N)
{
     
    // Corner Case
    if (start >= N)
    {
        return 0;
    }
 
    // Check if all the elements can
    // be taken
    if (N - start <= 2 * M)
    {
         
        // If the difference is less than
        // or equal to the available
        // chances then pick all numbers
        return sum(arr, start, N);
    }
 
    int psa = 0;
 
    // Sum of all numbers in the array
    int total = sum(arr, start, N);
 
    // Explore each element X
 
    // Skipping the k variable as per
    // the new updated chance of utility
    for(int x = 1; x < 2 * M + 1; x++)
    {
         
        // Sum of elements for Player A
        int psb = recursiveChoosing(arr, start + x,
                                    max(x, M), N);
 
        // Even chance sum can be obtained
        // by subtracting the odd chances
        // sum - total and picking up the
        // maximum from that
        psa = max(psa, total - psb);
    }
 
    // Return the maximum sum of odd chances
    return psa;
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 2, 7, 9, 4, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << recursiveChoosing(arr, 0, 1, N);
}
 
// This code is contributed by ipg2016107

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the maximum sum of
// array elements chosen by Player A
// according to the given criteria
static int recursiveChoosing(int arr[], int start,
                             int M, int N)
{
 
    // Corner Case
    if (start >= N)
    {
        return 0;
    }
 
    // Check if all the elements can
    // be taken
    if (N - start <= 2 * M)
    {
         
        // If the difference is less than
        // or equal to the available
        // chances then pick all numbers
        return sum(arr, start);
    }
 
    int psa = 0;
 
    // Sum of all numbers in the array
    int total = sum(arr, start);
 
    // Explore each element X
 
    // Skipping the k variable as per
    // the new updated chance of utility
    for(int x = 1; x < 2 * M + 1; x++)
    {
         
        // Sum of elements for Player A
        int psb = recursiveChoosing(arr, start + x,
                                    Math.max(x, M), N);
 
        // Even chance sum can be obtained
        // by subtracting the odd chances
        // sum - total and picking up the
        // maximum from that
        psa = Math.max(psa, total - psb);
    }
 
    // Return the maximum sum of odd chances
    return psa;
}
 
// Sum of all numbers in the array after start index
static int sum(int arr[], int start)
{
    int sum = 0;
    for(int i = start; i < arr.length; i++)
    {
        sum += arr[i];
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 2, 7, 9, 4, 4 };
    int N = arr.length;
 
    // Function Call
    System.out.print(recursiveChoosing(
        arr, 0, 1, N));
}
}
 
// This code is contributed by Kingash

Python3

# Python program for the above approach
 
# Function to find the maximum sum of
# array elements chosen by Player A
# according to the given criteria
def recursiveChoosing(arr, start, M):
   
    # Corner Case
    if start >= N:
        return 0
       
    # Check if all the elements can
    # be taken
    if N - start <= 2 * M:
       
        # If the difference is less than
        # or equal to the available
        # chances then pick all numbers
        return sum(arr[start:])
       
    psa = 0
     
    # Sum of all numbers in the array
    total = sum(arr[start:])
     
    # Explore each element X
     
    # Skipping the k variable as per
    # the new updated chance of utility
    for x in range(1, 2 * M + 1):
       
        # Sum of elements for Player A
        psb = recursiveChoosing(arr,
                            start + x, max(x, M))
         
        # Even chance sum can be obtained
        # by subtracting the odd chances
        # sum - total and picking up the
        # maximum from that
        psa = max(psa, total - psb) 
         
    # Return the maximum sum of odd chances
    return psa
 
# Driver Code
 
# Given array arr[]
arr = [2, 7, 9, 4, 4]
N = len(arr)
 
# Function Call
print(recursiveChoosing(arr, 0, 1))

C#

// C# program for the above approach
using System;
         
class GFG{
     
// Function to find the maximum sum of
// array elements chosen by Player A
// according to the given criteria
static int recursiveChoosing(int[] arr, int start,
                             int M, int N)
{
     
    // Corner Case
    if (start >= N)
    {
        return 0;
    }
  
    // Check if all the elements can
    // be taken
    if (N - start <= 2 * M)
    {
         
        // If the difference is less than
        // or equal to the available
        // chances then pick all numbers
        return sum(arr, start);
    }
  
    int psa = 0;
  
    // Sum of all numbers in the array
    int total = sum(arr, start);
  
    // Explore each element X
  
    // Skipping the k variable as per
    // the new updated chance of utility
    for(int x = 1; x < 2 * M + 1; x++)
    {
         
        // Sum of elements for Player A
        int psb = recursiveChoosing(arr, start + x,
                                    Math.Max(x, M), N);
  
        // Even chance sum can be obtained
        // by subtracting the odd chances
        // sum - total and picking up the
        // maximum from that
        psa = Math.Max(psa, total - psb);
    }
  
    // Return the maximum sum of odd chances
    return psa;
}
  
// Sum of all numbers in the array after start index
static int sum(int[] arr, int start)
{
    int sum = 0;
    for(int i = start; i < arr.Length; i++)
    {
        sum += arr[i];
    }
    return sum;
}
     
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int[] arr = { 2, 7, 9, 4, 4 };
    int N = arr.Length;
  
    // Function Call
    Console.WriteLine(recursiveChoosing(
        arr, 0, 1, N));
}
}
 
// This code is contributed by susmitakundugoaldanga

Javascript

<script>
 
// Javascript program for the above approach
 
// Sum of all numbers in the array
// after start index
function sum(arr, start, N)
{
    var sum1 = 0;
    for(var i = start; i < N; i++)
    {
        sum1 += arr[i];
    }
    return sum1;
}
 
// Function to find the maximum sum of
// array elements chosen by Player A
// according to the given criteria
function recursiveChoosing(arr, start, M, N)
{
     
    // Corner Case
    if (start >= N)
    {
        return 0;
    }
 
    // Check if all the elements can
    // be taken
    if (N - start <= 2 * M)
    {
         
        // If the difference is less than
        // or equal to the available
        // chances then pick all numbers
        return sum(arr, start, N);
    }
 
    var psa = 0;
 
    // Sum of all numbers in the array
    var total = sum(arr, start, N);
 
    // Explore each element X
 
    // Skipping the k variable as per
    // the new updated chance of utility
    for(var x = 1; x < 2 * M + 1; x++)
    {
         
        // Sum of elements for Player A
        var psb = recursiveChoosing(arr, start + x,
                                    Math.max(x, M), N);
 
        // Even chance sum can be obtained
        // by subtracting the odd chances
        // sum - total and picking up the
        // maximum from that
        psa = Math.max(psa, total - psb);
    }
 
    // Return the maximum sum of odd chances
    return psa;
}
 
// Driver Code
 
// Given array arr[]
var arr = [ 2, 7, 9, 4, 4 ];
var N = arr.length
 
// Function Call
document.write(recursiveChoosing(arr, 0, 1, N));
 
 
</script>
Producción: 

10

 

Complejidad de tiempo: O(K*2 N ), donde K está sobre el rango [1, 2*M]
Espacio auxiliar: O(N 2 )

Enfoque eficiente: el enfoque anterior también se puede optimizar mediante el uso de la programación dinámica , ya que tiene subproblemas superpuestos y una subestructura óptima que se pueden almacenar y utilizar más en las mismas llamadas recursivas.

Por lo tanto, la idea es usar un diccionario para almacenar el estado de cada llamada recursiva para que se pueda acceder más rápido al estado ya calculado y resulte en una menor complejidad de tiempo.

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 sum of
// array elements chosen by Player A
// according to the given criteria
int recursiveChoosing(int arr[], int start, int M, map<pair<int,int>,int> dp, int N)
{
    
    // Store the key
    pair<int,int> key(start, M);
 
    // Corner Case
    if(start >= N)
    {
        return 0;
    }
 
    // Check if all the elements can
    // be taken or not
    if(N - start <= 2 * M)
    {
        // If the difference is less than
        // or equal to the available
        // chances then pick all numbers
        int Sum = 0;
        for(int i = start; i < N; i++)
        {
            Sum = Sum + arr[i];
        }
        return Sum;
    }
 
    int sum = 0;
    for(int i = start; i < N; i++)
    {
      sum = sum + arr[i];
    }
    // Find the sum of array elements
    // over the range [start, N]
    int total = sum;
 
    // Checking if the current state is
    // previously calculated or not
 
    // If yes then return that value
    if(dp.find(key) != dp.end())
    {
        return dp[key];
    }
    int psa = 0;
    // Traverse over the range [1, 2 * M]
    for(int x = 1; x < 2 * M + 1; x++)
    {
        // Sum of elements for Player A
        int psb = recursiveChoosing(arr, start + x, max(x, M), dp, N);
        // Even chance sum can be obtained
        // by subtracting the odd chances
        // sum - total and picking up the
        // maximum from that
        psa = max(psa, total - psb);
    }
 
    // Storing the value in dictionary
    dp[key] = psa;
 
    // Return the maximum sum of odd chances
    return dp[key];
}
     
int main()
{
    int arr[] = {2, 7, 9, 4, 4};
    int N = sizeof(arr) / sizeof(arr[0]);
   
    // Stores the precomputed values
    map<pair<int,int>,int> dp;
   
    // Function Call
    cout << recursiveChoosing(arr, 0, 1, dp, N);
 
    return 0;
}
 
// This code is contributed by rameshtravel07.

Java

// Java program for the above approach
import java.util.*;
import java.awt.Point;
public class GFG
{
    // Function to find the maximum sum of
    // array elements chosen by Player A
    // according to the given criteria
    static int recursiveChoosing(int[] arr, int start, int M,
                                 HashMap<Point,Integer> dp)
    {
        
        // Store the key
        Point key = new Point(start, M);
   
        // Corner Case
        if(start >= arr.length)
        {
            return 0;
        }
   
        // Check if all the elements can
        // be taken or not
        if(arr.length - start <= 2 * M)
        {
           
            // If the difference is less than
            // or equal to the available
            // chances then pick all numbers
            int Sum = 0;
            for(int i = start; i < arr.length; i++)
            {
                Sum = Sum + arr[i];
            }
            return Sum;
        }
   
        int sum = 0;
        for(int i = start; i < arr.length; i++)
        {
          sum = sum + arr[i];
        }
       
        // Find the sum of array elements
        // over the range [start, N]
        int total = sum;
   
        // Checking if the current state is
        // previously calculated or not
   
        // If yes then return that value
        if(dp.containsKey(key))
        {
            return dp.get(key);
        }
        int psa = 0;
       
        // Traverse over the range [1, 2 * M]
        for(int x = 1; x < 2 * M + 1; x++)
        {
           
            // Sum of elements for Player A
            int psb = recursiveChoosing(arr, start + x, Math.max(x, M), dp);
           
            // Even chance sum can be obtained
            // by subtracting the odd chances
            // sum - total and picking up the
            // maximum from that
            psa = Math.max(psa, total - psb);
        }
   
        // Storing the value in dictionary
        dp.put(key, psa);
   
        // Return the maximum sum of odd chances
        return dp.get(key);
    }
     
    public static void main(String[] args) {
        int[] arr = {2, 7, 9, 4, 4};
        int N = arr.length;
       
        // Stores the precomputed values
        HashMap<Point,Integer> dp = new HashMap<Point,Integer>();
       
        // Function Call
        System.out.print(recursiveChoosing(arr, 0, 1, dp));
    }
}
 
// This code is contributed by divyesh072019.

Python3

# Python program for the above approach
 
# Function to find the maximum sum of
# array elements chosen by Player A
# according to the given criteria
def recursiveChoosing(arr, start, M, dp):
   
    # Store the key
    key = (start, M)
      
    # Corner Case
    if start >= N:
        return 0
       
    # Check if all the elements can
    # be taken or not
    if N - start <= 2 * M:
       
        # If the difference is less than
        # or equal to the available
        # chances then pick all numbers
        return sum(arr[start:])
       
        
    psa = 0
      
    # Find the sum of array elements
    # over the range [start, N]
    total = sum(arr[start:])
      
    # Checking if the current state is
    # previously calculated or not
     
    # If yes then return that value
    if key in dp:
        return dp[key]
        
    # Traverse over the range [1, 2 * M]
    for x in range(1, 2 * M + 1):
          
        # Sum of elements for Player A
        psb = recursiveChoosing(arr,
                          start + x, max(x, M), dp)
          
        # Even chance sum can be obtained
        # by subtracting the odd chances
        # sum - total and picking up the
        # maximum from that
        psa = max(psa, total - psb)
          
    # Storing the value in dictionary
    dp[key] = psa 
      
    # Return the maximum sum of odd chances
    return dp[key] 
 
# Driver Code
 
# Given array arr[]
arr = [2, 7, 9, 4, 4] 
N = len(arr) 
  
# Stores the precomputed values
dp = {} 
  
# Function Call
print(recursiveChoosing(arr, 0, 1, dp))

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find the maximum sum of
    // array elements chosen by Player A
    // according to the given criteria
    static int recursiveChoosing(int[] arr, int start, int M,
                                 Dictionary<Tuple<int,int>,int> dp)
    {
       
        // Store the key
        Tuple<int,int> key = new Tuple<int,int>(start, M);
  
        // Corner Case
        if(start >= arr.Length)
        {
            return 0;
        }
  
        // Check if all the elements can
        // be taken or not
        if(arr.Length - start <= 2 * M)
        {
            // If the difference is less than
            // or equal to the available
            // chances then pick all numbers
            int Sum = 0;
            for(int i = start; i < arr.Length; i++)
            {
                Sum = Sum + arr[i];
            }
            return Sum;
        }
  
        int sum = 0;
        for(int i = start; i < arr.Length; i++)
        {
          sum = sum + arr[i];
        }
        // Find the sum of array elements
        // over the range [start, N]
        int total = sum;
  
        // Checking if the current state is
        // previously calculated or not
  
        // If yes then return that value
        if(dp.ContainsKey(key))
        {
            return dp[key];
        }
        int psa = 0;
        // Traverse over the range [1, 2 * M]
        for(int x = 1; x < 2 * M + 1; x++)
        {
            // Sum of elements for Player A
            int psb = recursiveChoosing(arr, start + x, Math.Max(x, M), dp);
            // Even chance sum can be obtained
            // by subtracting the odd chances
            // sum - total and picking up the
            // maximum from that
            psa = Math.Max(psa, total - psb);
        }
  
        // Storing the value in dictionary
        dp[key] = psa;
  
        // Return the maximum sum of odd chances
        return dp[key];
    }
     
  // Driver code
  static void Main()
  {
    int[] arr = {2, 7, 9, 4, 4};
    int N = arr.Length;
  
    // Stores the precomputed values
    Dictionary<Tuple<int,int>,int> dp = new Dictionary<Tuple<int,int>,int>();
  
    // Function Call
    Console.Write(recursiveChoosing(arr, 0, 1, dp));
  }
}
 
// This code is contributed by divyeshrabadiya07.

Javascript

<script>
    // Javascript program for the above approach
     
    // Function to find the maximum sum of
    // array elements chosen by Player A
    // according to the given criteria
    function recursiveChoosing(arr, start, M, dp)
    {
        // Store the key
        let key = [start, M];
 
        // Corner Case
        if(start >= N)
        {
            return 0;
        }
 
        // Check if all the elements can
        // be taken or not
        if(N - start <= 2 * M)
        {
            // If the difference is less than
            // or equal to the available
            // chances then pick all numbers
            let sum = 0;
            for(let i = start; i < arr.length; i++)
            {
                sum = sum + arr[i];
            }
            return sum;
        }
 
 
        let psa = 0;
        let sum = 0;
        for(let i = start; i < arr.length; i++)
        {
          sum = sum + arr[i];
        }
        // Find the sum of array elements
        // over the range [start, N]
        let total = sum;
 
        // Checking if the current state is
        // previously calculated or not
 
        // If yes then return that value
        if(dp.has(key))
        {
            return dp[key];
        }
 
        // Traverse over the range [1, 2 * M]
        for(let x = 1; x < 2 * M + 1; x++)
        {
            // Sum of elements for Player A
            let psb = recursiveChoosing(arr,
                              start + x, Math.max(x, M), dp)
 
            // Even chance sum can be obtained
            // by subtracting the odd chances
            // sum - total and picking up the
            // maximum from that
            psa = Math.max(psa, total - psb);
        }
 
        // Storing the value in dictionary
        dp[key] = psa;
 
        // Return the maximum sum of odd chances
        return dp[key];
    }
     
    let arr = [2, 7, 9, 4, 4];
    let N = arr.length;
 
    // Stores the precomputed values
    let dp = new Map();
 
    // Function Call
    document.write(recursiveChoosing(arr, 0, 1, dp))
 
// This code is contributed by suresh07.
</script>
Producción: 

10

 

Complejidad de Tiempo: O(K*N 2 ), donde K está sobre el rango [1, 2*M]
Espacio Auxiliar: O(N 2 )

Publicación traducida automáticamente

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