Maximum score possible after performing given operations on an Array
Last Updated :
12 Jul, 2025
Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times:
- If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array.
- If the operation is even-numbered, the score is decremented by the sum of all elements of the current array.
- After every operation, either remove the first or the last element of the remaining array.
Examples:
Input: A = {1, 2, 3, 4, 2, 6}
Output: 13
Explanation:
The optimal operations are:
1. Operation 1 is odd.
-> So add the sum of the array to the score: Score = 0 + 18 = 18
-> remove 6 from last,
-> new array A = [1, 2, 3, 4, 2]
2. Operation 2 is even.
-> So subtract the sum of the array from the score: Score = 18 - 12 = 6
-> remove 2 from last,
-> new array A = [1, 2, 3, 4]
3. Operation 1 is odd.
-> So add the sum of the array to the score: Score = 6 + 10 = 16
-> remove 4 from last,
-> new array A = [1, 2, 3]
4. Operation 4 is even.
-> So subtract the sum of the array from the score: Score = 16 - 6 = 10
-> remove 1 from start,
-> new array A = [2, 3]
5. Operation 5 is odd.
-> So add the sum of the array to the score: Score = 10 + 5 = 15
-> remove 3 from last,
-> new array A = [2]
6. Operation 6 is even.
-> So subtract the sum of the array from the score: Score = 15 - 2 = 13
-> remove 2 from first,
-> new array A = []
The array is empty so no further operations are possible.
Input: A = [5, 2, 2, 8, 1, 16, 7, 9, 12, 4]
Output: 50
Naive approach
- In each operation, we have to remove either the leftmost or the rightmost element. A simple way would be to consider all possible ways to remove elements and for each branch compute the score and find the maximum score out of all. This can simply be done using recursion.
- The information we need to keep in each step would be
- The remaining array [l, r], where l represents the leftmost index and r the rightmost,
- The operation number, and
- The current score.
- In order to calculate the sum of any array from [l, r] in each recursive step optimally, we will keep a prefix sum array.
Using prefix sum array, new sum from [l, r] can be calculated in O(1) as:
Sum(l, r) = prefix_sum[r] - prefix_sum[l-1]
Below is the implementation of the above approach:
C++
// C++ program to find the maximum
// score after given operations
#include <bits/stdc++.h>
using namespace std;
// Function to calculate
// maximum score recursively
int maxScore(
int l, int r,
int prefix_sum[],
int num)
{
// Base case
if (l > r)
return 0;
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, by removing
// leftmost and rightmost element
// and selecting the maximum value
return current_sum
+ max(
maxScore(
l + 1, r,
prefix_sum,
num + 1),
maxScore(
l, r - 1,
prefix_sum,
num + 1));
}
// Function to find the max score
int findMaxScore(int a[], int n)
{
// Prefix sum array
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
// Driver code
int main()
{
int n = 6;
int A[n] = { 1, 2, 3, 4, 2, 6 };
cout << findMaxScore(A, n);
return 0;
}
Java
// Java program to find the maximum
// score after given operations
import java.util.*;
class GFG{
// Function to calculate
// maximum score recursively
static int maxScore(
int l, int r,
int prefix_sum[],
int num)
{
// Base case
if (l > r)
return 0;
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, by removing
// leftmost and rightmost element
// and selecting the maximum value
return current_sum
+ Math.max(maxScore(l + 1, r,
prefix_sum,
num + 1),
maxScore(l, r - 1,
prefix_sum,
num + 1));
}
// Function to find the max score
static int findMaxScore(int a[], int n)
{
// Prefix sum array
int prefix_sum[] = new int[n];
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
// Driver code
public static void main(String[] args)
{
int n = 6;
int A[] = { 1, 2, 3, 4, 2, 6 };
System.out.print(findMaxScore(A, n));
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 program to find the maximum
# score after given operations
# Function to calculate maximum
# score recursively
def maxScore(l, r, prefix_sum, num):
# Base case
if (l > r):
return 0;
# Sum of array in range (l, r)
if((l - 1) >= 0):
current_sum = (prefix_sum[r] -
prefix_sum[l - 1])
else:
current_sum = prefix_sum[r] - 0
# If the operation is even-numbered
# the score is decremented
if (num % 2 == 0):
current_sum *= -1;
# Exploring all paths, by removing
# leftmost and rightmost element
# and selecting the maximum value
return current_sum + max(maxScore(l + 1, r,
prefix_sum,
num + 1),
maxScore(l, r - 1,
prefix_sum,
num + 1));
# Function to find the max score
def findMaxScore(a, n):
# Prefix sum array
prefix_sum = [0] * n
prefix_sum[0] = a[0]
# Calculating prefix_sum
for i in range(1, n):
prefix_sum[i] = prefix_sum[i - 1] + a[i];
return maxScore(0, n - 1, prefix_sum, 1);
# Driver code
n = 6;
A = [ 1, 2, 3, 4, 2, 6 ]
ans = findMaxScore(A, n)
print(ans)
# This code is contributed by SoumikMondal
C#
// C# program to find the maximum
// score after given operations
using System;
class GFG{
// Function to calculate
// maximum score recursively
static int maxScore(
int l, int r,
int []prefix_sum,
int num)
{
// Base case
if (l > r)
return 0;
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, by removing
// leftmost and rightmost element
// and selecting the maximum value
return current_sum
+ Math.Max(maxScore(l + 1, r,
prefix_sum,
num + 1),
maxScore(l, r - 1,
prefix_sum,
num + 1));
}
// Function to find the max score
static int findMaxScore(int []a, int n)
{
// Prefix sum array
int []prefix_sum = new int[n];
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
// Driver code
public static void Main(String[] args)
{
int n = 6;
int []A = { 1, 2, 3, 4, 2, 6 };
Console.Write(findMaxScore(A, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to find the maximum
// score after given operations
// Function to calculate
// maximum score recursively
function maxScore(l, r, prefix_sum, num)
{
// Base case
if (l > r)
return 0;
// Sum of array in range (l, r)
let current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, by removing
// leftmost and rightmost element
// and selecting the maximum value
return current_sum
+ Math.max(
maxScore(
l + 1, r,
prefix_sum,
num + 1),
maxScore(
l, r - 1,
prefix_sum,
num + 1));
}
// Function to find the max score
function findMaxScore(a, n)
{
// Prefix sum array
let prefix_sum = new Uint8Array(n);
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (let i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
// Driver code
let n = 6;
let A = [ 1, 2, 3, 4, 2, 6 ];
document.write(findMaxScore(A, n));
// This code is contributed by Surbhi Tyagi.
</script>
Time complexity: O(2N)
Auxiliary space: O(N)
Efficient approach
- In the previous approach it can be observed that we are calculating same subproblems many times, i.e. it follows the property of Overlapping Subproblems. So we can use Dynamic programming to solve the problem
- In the recursive solution stated above, we only need to add memoization using a dp table. The states will be:
DP table states = dp[l][r][num]
where l and r represent the endpoints of the current array and num represents the operation number.
Below is the implementation of the Memoization approach of the recursive code:
C++
// C++ program to find the maximum
// Score after given operations
#include <bits/stdc++.h>
using namespace std;
// Memoizing by the use of a table
int dp[100][100][100];
// Function to calculate maximum score
int MaximumScoreDP(int l, int r,
int prefix_sum[],
int num)
{
// Bse case
if (l > r)
return 0;
// If the same state has
// already been computed
if (dp[l][r][num] != -1)
return dp[l][r][num];
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[l][r][num] = current_sum
+ max(
MaximumScoreDP(
l + 1, r,
prefix_sum,
num + 1),
MaximumScoreDP(
l, r - 1,
prefix_sum,
num + 1));
return dp[l][r][num];
}
// Function to find the max score
int findMaxScore(int a[], int n)
{
// Prefix sum array
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
// Initialising the DP table,
// -1 represents the subproblem
// hasn't been solved yet
memset(dp, -1, sizeof(dp));
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
// Driver code
int main()
{
int n = 6;
int A[n] = { 1, 2, 3, 4, 2, 6 };
cout << findMaxScore(A, n);
return 0;
}
Java
// Java program to find the maximum
// Score after given operations
class GFG{
// Memoizing by the use of a table
static int [][][]dp = new int[100][100][100];
// Function to calculate maximum score
static int MaximumScoreDP(int l, int r,
int prefix_sum[],
int num)
{
// Bse case
if (l > r)
return 0;
// If the same state has
// already been computed
if (dp[l][r][num] != -1)
return dp[l][r][num];
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[l][r][num] = current_sum
+ Math.max(
MaximumScoreDP(
l + 1, r,
prefix_sum,
num + 1),
MaximumScoreDP(
l, r - 1,
prefix_sum,
num + 1));
return dp[l][r][num];
}
// Function to find the max score
static int findMaxScore(int a[], int n)
{
// Prefix sum array
int []prefix_sum = new int[n];
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
// Initialising the DP table,
// -1 represents the subproblem
// hasn't been solved yet
for(int i = 0;i<100;i++){
for(int j = 0;j<100;j++){
for(int l=0;l<100;l++)
dp[i][j][l]=-1;
}
}
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
// Driver code
public static void main(String[] args)
{
int n = 6;
int A[] = { 1, 2, 3, 4, 2, 6 };
System.out.print(findMaxScore(A, n));
}
}
// This code contributed by sapnasingh4991
Python3
# python3 program to find the maximum
# Score after given operations
# Memoizing by the use of a table
dp = [[[-1 for x in range(100)]for y in range(100)]for z in range(100)]
# Function to calculate maximum score
def MaximumScoreDP(l, r, prefix_sum,
num):
# Bse case
if (l > r):
return 0
# If the same state has
# already been computed
if (dp[l][r][num] != -1):
return dp[l][r][num]
# Sum of array in range (l, r)
current_sum = prefix_sum[r]
if (l - 1 >= 0):
current_sum -= prefix_sum[l - 1]
# If the operation is even-numbered
# the score is decremented
if (num % 2 == 0):
current_sum *= -1
# Exploring all paths, and storing
# maximum value in DP table to avoid
# further repetitive recursive calls
dp[l][r][num] = (current_sum
+ max(
MaximumScoreDP(
l + 1, r,
prefix_sum,
num + 1),
MaximumScoreDP(
l, r - 1,
prefix_sum,
num + 1)))
return dp[l][r][num]
# Function to find the max score
def findMaxScore(a, n):
# Prefix sum array
prefix_sum = [0]*n
prefix_sum[0] = a[0]
# Calculating prefix_sum
for i in range(1, n):
prefix_sum[i] = prefix_sum[i - 1] + a[i]
# Initialising the DP table,
# -1 represents the subproblem
# hasn't been solved yet
global dp
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1)
# Driver code
if __name__ == "__main__":
n = 6
A = [1, 2, 3, 4, 2, 6]
print(findMaxScore(A, n))
C#
// C# program to find the maximum
// Score after given operations
using System;
public class GFG{
// Memoizing by the use of a table
static int [,,]dp = new int[100,100,100];
// Function to calculate maximum score
static int MaximumScoreDP(int l, int r,
int []prefix_sum,
int num)
{
// Bse case
if (l > r)
return 0;
// If the same state has
// already been computed
if (dp[l,r,num] != -1)
return dp[l,r,num];
// Sum of array in range (l, r)
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[l,r,num] = current_sum
+ Math.Max(
MaximumScoreDP(
l + 1, r,
prefix_sum,
num + 1),
MaximumScoreDP(
l, r - 1,
prefix_sum,
num + 1));
return dp[l,r,num];
}
// Function to find the max score
static int findMaxScore(int []a, int n)
{
// Prefix sum array
int []prefix_sum = new int[n];
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
// Initialising the DP table,
// -1 represents the subproblem
// hasn't been solved yet
for(int i = 0;i<100;i++){
for(int j = 0;j<100;j++){
for(int l=0;l<100;l++)
dp[i,j,l]=-1;
}
}
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
// Driver code
public static void Main(String[] args)
{
int n = 6;
int []A = { 1, 2, 3, 4, 2, 6 };
Console.Write(findMaxScore(A, n));
}
}
// This code contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program to find the maximum
// Score after given operations
// Memoizing by the use of a table
let dp = new Array(100);
// Initialising the DP table,
// -1 represents the subproblem
// hasn't been solved yet
for(let i=0;i<100;i++)
{
dp[i]=new Array(100);
for(let j=0;j<100;j++)
{
dp[i][j]=new Array(100);
for(let k=0;k<100;k++)
{
dp[i][j][k]=-1;
}
}
}
// Function to calculate maximum score
function MaximumScoreDP(l,r,prefix_sum,num)
{
// Bse case
if (l > r)
return 0;
// If the same state has
// already been computed
if (dp[l][r][num] != -1)
return dp[l][r][num];
// Sum of array in range (l, r)
let current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
// If the operation is even-numbered
// the score is decremented
if (num % 2 == 0)
current_sum *= -1;
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[l][r][num] = current_sum
+ Math.max(
MaximumScoreDP(
l + 1, r,
prefix_sum,
num + 1),
MaximumScoreDP(
l, r - 1,
prefix_sum,
num + 1));
return dp[l][r][num];
}
// Function to find the max score
function findMaxScore(a,n)
{
// Prefix sum array
let prefix_sum = new Array(n);
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (let i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
// Initialising the DP table,
// -1 represents the subproblem
// hasn't been solved yet
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
// Driver code
let n = 6;
let A=[1, 2, 3, 4, 2, 6 ];
document.write(findMaxScore(A, n));
// This code is contributed by rag2127
</script>
Time complexity: O(N^3)
Auxiliary space: O(N^3)
Efficient approach : DP tabulation (iterative)
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls. In this approach we use 3D DP store computation of subproblems and find the final result using iteration and not with the help of recursion.
Steps that were to follow the above approach:
- Initialize a 3D DP array dp of size n x n x n.
- Calculate the prefix sum of the input array a in an array prefix_sum.
- Fill the dp table diagonally, considering all possible lengths of subarrays.
- For each subarray of length len, consider all possible starting indices i, ending indices j, and even-numbered operations num.
- Calculate the current sum of the subarray based on prefix_sum and the even/odd nature of the operation.
- If the subarray has only one element (i.e., i == j), store the current sum in dp[i][j][num].
- Otherwise, calculate the maximum score by exploring all possible paths, and store the maximum value in dp[i][j][num] to avoid further repetitive recursive calls.
- Return dp[0][n - 1][1] as the maximum score.
Below is the implementation of the above approach:
C++
// C++ program to find the maximum
// Score after given operations
#include <bits/stdc++.h>
using namespace std;
// Function to find the max score
int findMaxScore(int a[], int n)
{
// initialize Dp to store computation of subproblems
int dp[n][n][n] = { 0 };
// Prefix sum array
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + a[i];
}
// Filling the table diagonally
for (int len = 1; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
for (int num = 1; num <= n; num++) {
// Sum of array in range (l, r)
int current_sum
= prefix_sum[j]
- (i - 1 >= 0 ? prefix_sum[i - 1]
: 0);
if (num % 2 == 0) {
// If the operation is even-numbered
// the score is decremented
current_sum *= -1;
}
if (i == j) {
dp[i][j][num] = current_sum;
}
else {
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[i][j][num] = max(
current_sum + dp[i + 1][j][num + 1],
current_sum
+ dp[i][j - 1][num + 1]);
}
}
}
}
return dp[0][n - 1][1];
}
// Driver code
int main()
{
int n = 6;
int A[n] = { 1, 2, 3, 4, 2, 6 };
cout << findMaxScore(A, n);
return 0;
}
Java
import java.util.*;
class GFG {
// Function to find the max score
static int findMaxScore(int[] a, int n)
{
// Initialize DP to store computation of subproblems
int[][][] dp = new int[n + 3][n + 3][n + 3];
// Prefix sum array
int[] prefixSum = new int[n];
prefixSum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + a[i];
}
// Filling the table diagonally
for (int length = 1; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
for (int num = 1; num <= n; num++) {
// Sum of array in range (l, r)
int currentSum
= prefixSum[j]
- (i - 1 >= 0 ? prefixSum[i - 1]
: 0);
// If the operation is even-numbered,
// the score is decremented
if (num % 2 == 0) {
currentSum *= -1;
}
if (i == j) {
dp[i][j][num] = currentSum;
}
else {
// Exploring all paths, and storing
// maximum value in DP table
dp[i][j][num] = Math.max(
currentSum
+ dp[i + 1][j][num + 1],
currentSum
+ dp[i][j - 1][num + 1]);
}
}
}
}
return dp[0][n - 1][1];
}
// Driver code
public static void main(String[] args)
{
int n = 6;
int[] A = { 1, 2, 3, 4, 2, 6 };
System.out.println(findMaxScore(A, n));
}
}
Python3
# Python3 program to find the maximum
# Score after given operations
def findMaxScore(a, n):
# Initialize DP to store computation of subproblems
dp = [[[0] * (n + 3) for _ in range(n+3)] for _ in range(n+3)]
# Prefix sum array
prefix_sum = [0] * n
prefix_sum[0] = a[0]
# Calculating prefix_sum
for i in range(1, n):
prefix_sum[i] = prefix_sum[i - 1] + a[i]
# Filling the table diagonally
for length in range(1, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for num in range(1, n + 1):
# Sum of array in range (l, r)
current_sum = prefix_sum[j] - (prefix_sum[i - 1] if i - 1 >= 0 else 0)
if num % 2 == 0:
# If the operation is even-numbered, the score
# is decremented
current_sum *= -1
if i == j:
dp[i][j][num] = current_sum
else:
# Exploring all paths and storing maximum value in
# DP table
dp[i][j][num] = max(current_sum + dp[i + 1][j][num + 1],
current_sum + dp[i][j - 1][num + 1])
return dp[0][n - 1][1]
# Driver code
n = 6
A = [1, 2, 3, 4, 2, 6]
print(findMaxScore(A, n))
C#
using System;
class GFG {
// Function to find the max score
static int FindMaxScore(int[] a, int n)
{
// Initialize DP to store computation of subproblems
int[, , ] dp = new int[n + 3, n + 3, n + 3];
// Prefix sum array
int[] prefixSum = new int[n];
prefixSum[0] = a[0];
// Calculating prefix_sum
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + a[i];
}
// Filling the table diagonally
for (int length = 1; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
for (int num = 1; num <= n; num++) {
// Sum of array in range (l, r)
int currentSum
= prefixSum[j]
- (i - 1 >= 0 ? prefixSum[i - 1]
: 0);
// If the operation is even-numbered,
// the score is decremented
if (num % 2 == 0) {
currentSum *= -1;
}
if (i == j) {
dp[i, j, num] = currentSum;
}
else {
// Exploring all paths, and storing
// maximum value in DP table
dp[i, j, num] = Math.Max(
currentSum
+ dp[i + 1, j, num + 1],
currentSum
+ dp[i, j - 1, num + 1]);
}
}
}
}
return dp[0, n - 1, 1];
}
// Driver code
static void Main()
{
int n = 6;
int[] A = { 1, 2, 3, 4, 2, 6 };
Console.WriteLine(FindMaxScore(A, n));
}
}
JavaScript
// Javascript program to find the maximum
// Score after given operations
// Function to find the max score
function findMaxScore(a, n) {
// initialize Dp to store computation of subproblems
let dp = new Array(n).fill(0).map(() => new Array(n).fill(0).map(() => new Array(n).fill(0)));
// Prefix sum array
let prefix_sum = new Array(n).fill(0);
prefix_sum[0] = a[0];
// Calculating prefix_sum
for (let i = 1; i < n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + a[i];
}
// Filling the table diagonally
for (let len = 1; len <= n; len++) {
for (let i = 0; i + len - 1 < n; i++) {
let j = i + len - 1;
for (let num = 1; num <= n; num++) {
// Sum of array in range (l, r)
let current_sum = prefix_sum[j] - (i - 1 >= 0 ? prefix_sum[i - 1] : 0);
if (num % 2 === 0) {
// If the operation is even-numbered
// the score is decremented
current_sum *= -1;
}
if (i === j) {
dp[i][j][num] = current_sum;
}
else {
// Exploring all paths, and storing
// maximum value in DP table to avoid
// further repetitive recursive calls
dp[i][j][num] = Math.max(
current_sum + dp[i + 1][j][num + 1],
current_sum + dp[i][j - 1][num + 1]
);
}
}
}
}
return dp[0][n - 1][1];
}
// Driver code
let n = 6;
let A = [1, 2, 3, 4, 2, 6];
console.log(findMaxScore(A, n));
Output:
13
Time complexity: O(N^3)
Auxiliary space: O(N^3)
Efficient Approach: Space Optimization
In previous approach the current value dp[i][j][num] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 2D matrix instead of 3d array to store the computations.
Follow the step below to implement the above idea:
- Initialize a 2D array dp of size n x n to store maximum scores.
- Calculate the prefix sum array prefix_sum by iterating through the input array a[] and adding the previous prefix sum.
- Iterate over different lengths of subarrays (len) and starting indices of subarrays (i).
- Iterate over the number of elements to consider in the subarray (num).
- Calculate the current sum of the subarray and handle even/odd number conditions.
- Determine the maximum score by choosing between including or excluding the current element.
- Return the maximum score for the entire array considering 1 element (dp[0][1]).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxScore(int a[], int n)
{
// DP array to store maximum scores
int dp[n][n] = {0};
// Prefix sum array to calculate subarray sums
int prefix_sum[n] = {0};
// Initialize the prefix sum with the first element
prefix_sum[0] = a[0];
for (int i = 1; i < n; i++) {
// Calculate prefix sum
prefix_sum[i] = prefix_sum[i - 1] + a[i];
}
for (int len = 1; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
for (int num = 1; num <= n; num++) {
int current_sum = prefix_sum[j] - (i - 1 >= 0 ? prefix_sum[i - 1] : 0);
// Calculate the sum of the current subarray
if (num % 2 == 0) {
// Multiply sum by -1 if num is even
current_sum *= -1;
}
if (i == j) {
// Base case: subarray has only one element
dp[i][num] = current_sum;
} else {
// Choose the maximum score among two options:
// 1. Include the current element and move to the next element
// 2. Exclude the current element and move to the next element
dp[i][num] = max(current_sum + dp[i + 1][num + 1], current_sum + dp[i][num + 1]);
}
}
}
}
return dp[0][1];
}
int main()
{
int n = 6;
int A[] = {1, 2, 3, 4, 2, 6};
cout << findMaxScore(A, n) << endl;
return 0;
}
// --by bhardwajji
Java
public class MaxScore {
static int findMaxScore(int[] arr, int n) {
// DP array to store maximum scores
int[][] dp = new int[n][n + 1];
// Prefix sum array to calculate subarray sums
int[] prefixSum = new int[n];
// Initialize the prefix sum with the first element
prefixSum[0] = arr[0];
for (int i = 1; i < n; i++) {
// Calculate prefix sum
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
for (int length = 1; length <= n; length++) {
for (int i = 0; i <= n - length; i++) {
int j = i + length - 1;
for (int num = 1; num <= n; num++) {
int currentSum = prefixSum[j] - ((i - 1 >= 0) ? prefixSum[i - 1] : 0);
// Calculate the sum of the current subarray
if (num % 2 == 0) {
// Multiply sum by -1 if num is even
currentSum *= -1;
}
if (i == j) {
// Base case: subarray has only one element
dp[i][num] = currentSum;
} else {
// Choose the maximum score among two options:
// 1. Include the current element and move to the next element
// 2. Exclude the current element and move to the next element
dp[i][num] = Math.max(
currentSum + ((num + 1 <= n) ? dp[i + 1][num + 1] : 0),
currentSum + ((num + 1 <= n) ? dp[i][num + 1] : 0)
);
}
}
}
}
return dp[0][1];
}
public static void main(String[] args) {
int n = 6;
int[] A = {1, 2, 3, 4, 2, 6};
System.out.println(findMaxScore(A, n));
}
}
Python3
def findMaxScore(arr, n):
# DP array to store maximum scores
dp = [[0] * (n + 1) for _ in range(n)]
# Prefix sum array to calculate subarray sums
prefix_sum = [0] * n
# Initialize the prefix sum with the first element
prefix_sum[0] = arr[0]
for i in range(1, n):
# Calculate prefix sum
prefix_sum[i] = prefix_sum[i - 1] + arr[i]
for length in range(1, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for num in range(1, n + 1):
current_sum = prefix_sum[j] - (prefix_sum[i - 1] if i - 1 >= 0 else 0)
# Calculate the sum of the current subarray
if num % 2 == 0:
# Multiply sum by -1 if num is even
current_sum *= -1
if i == j:
# Base case: subarray has only one element
dp[i][num] = current_sum
else:
# Choose the maximum score among two options:
# 1. Include the current element and move to the next element
# 2. Exclude the current element and move to the next element
dp[i][num] = max(current_sum + (dp[i + 1][num + 1] if num + 1 <= n else 0),
current_sum + dp[i][num + 1] if num + 1 <= n else 0)
return dp[0][1]
def main():
n = 6
A = [1, 2, 3, 4, 2, 6]
print(findMaxScore(A, n))
if __name__ == "__main__":
main()
C#
using System;
class MaxScoreSubarray {
static int FindMaxScore(int[] arr, int n)
{
// DP array to store maximum scores
int[, ] dp = new int[n, n + 1];
// Prefix sum array to calculate subarray sums
int[] prefixSum = new int[n];
// Initialize the prefix sum with the first element
prefixSum[0] = arr[0];
for (int i = 1; i < n; i++) {
// Calculate prefix sum
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
for (int length = 1; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
for (int num = 1; num <= n; num++) {
int currentSum
= prefixSum[j]
- (i - 1 >= 0 ? prefixSum[i - 1]
: 0);
// Calculate the sum of the current
// subarray
if (num % 2 == 0) {
// Multiply sum by -1 if num is even
currentSum *= -1;
}
if (i == j) {
// Base case: subarray has only one
// element
dp[i, num] = currentSum;
}
else {
// Choose the maximum score among
// two options:
// 1. Include the current element
// and move to the next element
// 2. Exclude the current element
// and move to the next element
dp[i, num] = Math.Max(
currentSum
+ (num + 1 <= n
? dp[i + 1, num + 1]
: 0),
currentSum
+ (num + 1 <= n
? dp[i, num + 1]
: 0));
}
}
}
}
return dp[0, 1];
}
static void Main()
{
int n = 6;
int[] A = { 1, 2, 3, 4, 2, 6 };
Console.WriteLine(FindMaxScore(A, n));
}
}
JavaScript
function GFG(a, n) {
// Initialize an array to store maximum scores
const dp = new Array(n).fill(0).map(() => new Array(n).fill(0));
// Initialize an array for prefix sums to
// calculate subarray sums
const prefixSum = new Array(n).fill(0);
// Initialize the prefix sum with
// the first element
prefixSum[0] = a[0];
for (let i = 1; i < n; i++) {
// Calculate prefix sum
prefixSum[i] = prefixSum[i - 1] + a[i];
}
for (let len = 1; len <= n; len++) {
for (let i = 0; i + len - 1 < n; i++) {
const j = i + len - 1;
for (let num = 1; num <= n; num++) {
let currentSum = prefixSum[j] - (i - 1 >= 0 ? prefixSum[i - 1] : 0);
// Calculate the sum of the current subarray
if (num % 2 === 0) {
// Multiply sum by -1 if num is even
currentSum *= -1;
}
if (i === j) {
// Base case: subarray has only one element
dp[i][num] = currentSum;
} else {
dp[i][num] = Math.max(currentSum + dp[i + 1][num + 1], currentSum + dp[i][num + 1]);
}
}
}
}
return dp[0][1];
}
function main() {
const n = 6;
const A = [1, 2, 3, 4, 2, 6];
console.log(GFG(A, n));
}
main();
Time complexity: O(N^3)
Auxiliary space: O(N^2)
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