Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning
Last Updated :
15 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem