Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning
Last Updated :
25 Oct, 2021
Given an array arr[] consisting of N integers and an integer M (initially 1), the task is to find the maximum sum of array elements chosen by Player A when two players A and B plays the game optimally according to the following rules:
- Player A starts the game.
- At every chance, X number of elements can be chosen from the beginning of the array, where X is inclusive over the range [1, 2*M] is chosen by the respective player in their turn.
- After choosing array elements in the above steps, remove those elements from the array and update the value of M as the maximum of X and M.
- The above process will continue till all the array elements are chosen.
Examples:
Input: arr[] = {2, 7, 9, 4, 4}
Output: 10
Explanation:
Initially the array is arr[] = {2, 7, 9, 4, 4} and the value of M = 1, Below are the order of ch0osing array elements by both the players:
Player A: The number of elements can be chosen over the range [1, 2*M] i.e., [1, 2]. So, choose element {2} and remove it. Now the array modifies to {7, 9, 4, 4} and the value of M is max(M, X) = max(1, 1) = 1(X is 1).
Player B: The number of elements can be chosen over the range [1, 2*M] i.e., [1, 2]. So, choose element {7, 9} and remove it. Now the array modifies to {4, 4} and the value of M is max(M, X) = max(1, 2) = 2(X is 2).
Player A: The number of elements can be chosen over the range [1, 2*2] i.e., [1, 1]. So, choose element {4, 4} and remove it. Now the array becomes empty.
Therefore, the sum of elements chosen by the Player A is 2 + 4 + 4 = 10.
Input: arr[] = {1}
Output: 1
Naive Approach: The simplest approach is to solve the given problem is to use recursion and generate all possible combinations of choosing elements for both the players from the beginning according to the given rules and print the maximum sum of chosen elements obtained for Player A. Follow the below steps to solve the given problem:
- Declare a recursive function, say recursiveChoosing(arr, start, M) that takes parameters array, starting index of the current array, and initial value of M and perform the following operations in this function:
- If the value of start is greater than N, then return 0.
- If the value of (N - start) is at most 2*M, then return the sum of the element of the array from the index start for the respective score of the player.
- Initialize a maxSum as 0 that stores the maximum sum of array elements chosen by Player A.
- Find the total sum of the array elements from the start and store it in a variable, say total.
- Iterate over the range [1, 2*M], and perform the following steps:
- For each element X, chooses X elements from the start and recursively calls for choosing elements from the remaining (N - X) elements. Let the value returned by this call be stored in maxSum.
- After the above recursive call ends update the value of maxSum to the maximum of maxSum and (total - maxSum).
- Return the value of maxSum in each recursive call.
- After completing the above steps, print the value returned by the function recursiveChoosing(arr, 0, 1).
Below is the implementation of the above approach:
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>
Time Complexity: O(K*2N), where K is over the range [1, 2*M]
Auxiliary Space: O(N2)
Efficient Approach: The above approach can also be optimized by using Dynamic Programming as it has Overlapping Subproblems and Optimal Substructure that can be stored and used further in the same recursive calls.
Therefore, the idea is to use a dictionary to store the state of each recursive call so that the already computed state can be accessed faster and result in less time complexity.
Below is the implementation of the above approach:
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>
Time Complexity: O(K*N2), where K is over the range [1, 2*M]
Auxiliary Space: O(N2)
Similar Reads
Make all array elements even by replacing any pair of array elements with their sum
Given an array arr[] consisting of N positive integers, the task is to make all array elements even by replacing any pair of array elements with their sum. Examples: Input: arr[] = {5, 6, 3, 7, 20}Output: 3Explanation: Operation 1: Replace arr[0] and arr[2] by their sum ( = 5 + 3 = 8) modifies arr[]
5 min read
Maximize sum of K elements selected from a Matrix such that each selected element must be preceded by selected row elements
Given a 2D array arr[][] of size N * M, and an integer K, the task is to select K elements with maximum possible sum such that if an element arr[i][j] is selected, then all the elements from the ith row present before the jth column needs to be selected. Examples: Input: arr[][] = {{10, 10, 100, 30}
10 min read
Maximize sum of atmost K elements in array by taking only corner elements | Set 2
Given an array arr[] and an integer K, the task is to find and maximize the sum of at most K elements in the Array by taking only corner elements. A corner element is an element from the start of the array or from the end of the array. Examples: Input: N = 8, arr[] = {6, -1, 14, -15, 2, 1, 2, -5}, K
12 min read
Maximize sum by selecting M elements from the start or end of rows of a Matrix
Given a 2D array Blocks[][] consisting of N rows of variable length. The task is to select at most M elements with the maximum possible sum from Blocks[][] from either the start or end of a row. Examples: Input: N = 3, M = 4 Blocks[][] = {{2, 3, 5}, {-1, 7}, {8, 10}}Output: 30Explanation: Select {5}
11 min read
Maximize difference between odd and even indexed array elements by shift operations
Given an array arr[] of size N, the task is to maximize the absolute difference between the sum of even indexed elements and the sum of odd indexed elements by left shift or right shift of array elements any number of times. Examples: Input: arr[] = {332, 421, 215, 584, 232}Output: 658Explanation: C
9 min read
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1
Given a positive integer N, the task is to construct an array of length N and find the maximum value at index K such that the sum of all the array elements is at most M and the absolute difference between any two consecutive array elements is at most 1.Examples:Input: N = 3, M = 7, K = 1Output: 3Exp
6 min read
Maximize difference between odd and even-indexed array elements by rotating their binary representations
Given an array arr[] consisting of N positive integers, the task is to find the maximum absolute difference between the sum of the array elements placed at even indices and those at odd indices of the array by rotating their binary representations any number of times. Consider only 8-bit representat
12 min read
Ways to make sum of odd and even indexed elements equal by removing an array element
Given an array, arr[] of size n, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal.Examples:Input: arr[] = [ 2, 1, 6, 4 ] Output: 1 Explanation: Removing arr[1] from the array modifies ar
10 min read
Make all array elements even by replacing adjacent pair of array elements with their sum
Given an array arr[] of size N, the task is to make all array elements even by replacing a pair of adjacent elements with their sum. Examples: Input: arr[] = { 2, 4, 5, 11, 6 }Output: 1Explanation:Replacing a pair (arr[2], arr[3]) with their sum ( = 5 + 11 = 16) modifies arr[] to { 2, 4, 16, 16, 6 }
8 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:
9 min read