Maximum score possible after performing given operations on an Array
Last Updated :
03 Jan, 2024
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++
#include <bits/stdc++.h>
using namespace std;
int maxScore(
int l, int r,
int prefix_sum[],
int num)
{
if (l > r)
return 0;
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
return current_sum
+ max(
maxScore(
l + 1, r,
prefix_sum,
num + 1),
maxScore(
l, r - 1,
prefix_sum,
num + 1));
}
int findMaxScore( int a[], int n)
{
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
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{
static int maxScore(
int l, int r,
int prefix_sum[],
int num)
{
if (l > r)
return 0 ;
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1 ]
: 0 );
if (num % 2 == 0 )
current_sum *= - 1 ;
return current_sum
+ Math.max(maxScore(l + 1 , r,
prefix_sum,
num + 1 ),
maxScore(l, r - 1 ,
prefix_sum,
num + 1 ));
}
static int findMaxScore( int a[], int n)
{
int prefix_sum[] = new int [n];
prefix_sum[ 0 ] = a[ 0 ];
for ( int i = 1 ; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1 ] + a[i];
}
return maxScore( 0 , n - 1 ,
prefix_sum, 1 );
}
public static void main(String[] args)
{
int n = 6 ;
int A[] = { 1 , 2 , 3 , 4 , 2 , 6 };
System.out.print(findMaxScore(A, n));
}
}
|
Python3
def maxScore(l, r, prefix_sum, num):
if (l > r):
return 0 ;
if ((l - 1 ) > = 0 ):
current_sum = (prefix_sum[r] -
prefix_sum[l - 1 ])
else :
current_sum = prefix_sum[r] - 0
if (num % 2 = = 0 ):
current_sum * = - 1 ;
return current_sum + max (maxScore(l + 1 , r,
prefix_sum,
num + 1 ),
maxScore(l, r - 1 ,
prefix_sum,
num + 1 ));
def findMaxScore(a, n):
prefix_sum = [ 0 ] * n
prefix_sum[ 0 ] = a[ 0 ]
for i in range ( 1 , n):
prefix_sum[i] = prefix_sum[i - 1 ] + a[i];
return maxScore( 0 , n - 1 , prefix_sum, 1 );
n = 6 ;
A = [ 1 , 2 , 3 , 4 , 2 , 6 ]
ans = findMaxScore(A, n)
print (ans)
|
C#
using System;
class GFG{
static int maxScore(
int l, int r,
int []prefix_sum,
int num)
{
if (l > r)
return 0;
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
return current_sum
+ Math.Max(maxScore(l + 1, r,
prefix_sum,
num + 1),
maxScore(l, r - 1,
prefix_sum,
num + 1));
}
static int findMaxScore( int []a, int n)
{
int []prefix_sum = new int [n];
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
public static void Main(String[] args)
{
int n = 6;
int []A = { 1, 2, 3, 4, 2, 6 };
Console.Write(findMaxScore(A, n));
}
}
|
Javascript
<script>
function maxScore(l, r, prefix_sum, num)
{
if (l > r)
return 0;
let current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
return current_sum
+ Math.max(
maxScore(
l + 1, r,
prefix_sum,
num + 1),
maxScore(
l, r - 1,
prefix_sum,
num + 1));
}
function findMaxScore(a, n)
{
let prefix_sum = new Uint8Array(n);
prefix_sum[0] = a[0];
for (let i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return maxScore(0, n - 1,
prefix_sum, 1);
}
let n = 6;
let A = [ 1, 2, 3, 4, 2, 6 ];
document.write(findMaxScore(A, n));
</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++
#include <bits/stdc++.h>
using namespace std;
int dp[100][100][100];
int MaximumScoreDP( int l, int r,
int prefix_sum[],
int num)
{
if (l > r)
return 0;
if (dp[l][r][num] != -1)
return dp[l][r][num];
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
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];
}
int findMaxScore( int a[], int n)
{
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
memset (dp, -1, sizeof (dp));
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
int main()
{
int n = 6;
int A[n] = { 1, 2, 3, 4, 2, 6 };
cout << findMaxScore(A, n);
return 0;
}
|
Java
class GFG{
static int [][][]dp = new int [ 100 ][ 100 ][ 100 ];
static int MaximumScoreDP( int l, int r,
int prefix_sum[],
int num)
{
if (l > r)
return 0 ;
if (dp[l][r][num] != - 1 )
return dp[l][r][num];
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1 ]
: 0 );
if (num % 2 == 0 )
current_sum *= - 1 ;
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];
}
static int findMaxScore( int a[], int n)
{
int []prefix_sum = new int [n];
prefix_sum[ 0 ] = a[ 0 ];
for ( int i = 1 ; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1 ] + a[i];
}
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 );
}
public static void main(String[] args)
{
int n = 6 ;
int A[] = { 1 , 2 , 3 , 4 , 2 , 6 };
System.out.print(findMaxScore(A, n));
}
}
|
Python3
dp = [[[ - 1 for x in range ( 100 )] for y in range ( 100 )] for z in range ( 100 )]
def MaximumScoreDP(l, r, prefix_sum,
num):
if (l > r):
return 0
if (dp[l][r][num] ! = - 1 ):
return dp[l][r][num]
current_sum = prefix_sum[r]
if (l - 1 > = 0 ):
current_sum - = prefix_sum[l - 1 ]
if (num % 2 = = 0 ):
current_sum * = - 1
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]
def findMaxScore(a, n):
prefix_sum = [ 0 ] * n
prefix_sum[ 0 ] = a[ 0 ]
for i in range ( 1 , n):
prefix_sum[i] = prefix_sum[i - 1 ] + a[i]
global dp
return MaximumScoreDP(
0 , n - 1 ,
prefix_sum, 1 )
if __name__ = = "__main__" :
n = 6
A = [ 1 , 2 , 3 , 4 , 2 , 6 ]
print (findMaxScore(A, n))
|
C#
using System;
public class GFG{
static int [,,]dp = new int [100,100,100];
static int MaximumScoreDP( int l, int r,
int []prefix_sum,
int num)
{
if (l > r)
return 0;
if (dp[l,r,num] != -1)
return dp[l,r,num];
int current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
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];
}
static int findMaxScore( int []a, int n)
{
int []prefix_sum = new int [n];
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
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);
}
public static void Main(String[] args)
{
int n = 6;
int []A = { 1, 2, 3, 4, 2, 6 };
Console.Write(findMaxScore(A, n));
}
}
|
Javascript
<script>
let dp = new Array(100);
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 MaximumScoreDP(l,r,prefix_sum,num)
{
if (l > r)
return 0;
if (dp[l][r][num] != -1)
return dp[l][r][num];
let current_sum
= prefix_sum[r]
- (l - 1 >= 0
? prefix_sum[l - 1]
: 0);
if (num % 2 == 0)
current_sum *= -1;
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 findMaxScore(a,n)
{
let prefix_sum = new Array(n);
prefix_sum[0] = a[0];
for (let i = 1; i < n; i++) {
prefix_sum[i]
= prefix_sum[i - 1] + a[i];
}
return MaximumScoreDP(
0, n - 1,
prefix_sum, 1);
}
let n = 6;
let A=[1, 2, 3, 4, 2, 6 ];
document.write(findMaxScore(A, n));
</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++
#include <bits/stdc++.h>
using namespace std;
int findMaxScore( int a[], int n)
{
int dp[n][n][n] = { 0 };
int prefix_sum[n] = { 0 };
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
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);
if (num % 2 == 0) {
current_sum *= -1;
}
if (i == j) {
dp[i][j][num] = current_sum;
}
else {
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];
}
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 {
static int findMaxScore( int [] a, int n)
{
int [][][] dp = new int [n + 3 ][n + 3 ][n + 3 ];
int [] prefixSum = new int [n];
prefixSum[ 0 ] = a[ 0 ];
for ( int i = 1 ; i < n; i++) {
prefixSum[i] = prefixSum[i - 1 ] + a[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 );
if (num % 2 == 0 ) {
currentSum *= - 1 ;
}
if (i == j) {
dp[i][j][num] = currentSum;
}
else {
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 ];
}
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(a, n):
dp = [[[ 0 ] * (n + 3 ) for _ in range (n + 3 )] for _ in range (n + 3 )]
prefix_sum = [ 0 ] * n
prefix_sum[ 0 ] = a[ 0 ]
for i in range ( 1 , n):
prefix_sum[i] = prefix_sum[i - 1 ] + a[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 )
if num % 2 = = 0 :
current_sum * = - 1
if i = = j:
dp[i][j][num] = current_sum
else :
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 ]
n = 6
A = [ 1 , 2 , 3 , 4 , 2 , 6 ]
print (findMaxScore(A, n))
|
C#
using System;
class GFG {
static int FindMaxScore( int [] a, int n)
{
int [, , ] dp = new int [n + 3, n + 3, n + 3];
int [] prefixSum = new int [n];
prefixSum[0] = a[0];
for ( int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + a[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);
if (num % 2 == 0) {
currentSum *= -1;
}
if (i == j) {
dp[i, j, num] = currentSum;
}
else {
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];
}
static void Main()
{
int n = 6;
int [] A = { 1, 2, 3, 4, 2, 6 };
Console.WriteLine(FindMaxScore(A, n));
}
}
|
Javascript
function findMaxScore(a, n) {
let dp = new Array(n).fill(0).map(() => new Array(n).fill(0).map(() => new Array(n).fill(0)));
let prefix_sum = new Array(n).fill(0);
prefix_sum[0] = a[0];
for (let i = 1; i < n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + a[i];
}
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++) {
let current_sum = prefix_sum[j] - (i - 1 >= 0 ? prefix_sum[i - 1] : 0);
if (num % 2 === 0) {
current_sum *= -1;
}
if (i === j) {
dp[i][j][num] = current_sum;
}
else {
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];
}
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)
{
int dp[n][n] = {0};
int prefix_sum[n] = {0};
prefix_sum[0] = a[0];
for ( int i = 1; i < n; i++) {
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);
if (num % 2 == 0) {
current_sum *= -1;
}
if (i == j) {
dp[i][num] = current_sum;
} else {
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;
}
|
Java
public class MaxScore {
static int findMaxScore( int [] arr, int n) {
int [][] dp = new int [n][n + 1 ];
int [] prefixSum = new int [n];
prefixSum[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
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 );
if (num % 2 == 0 ) {
currentSum *= - 1 ;
}
if (i == j) {
dp[i][num] = currentSum;
} else {
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 = [[ 0 ] * (n + 1 ) for _ in range (n)]
prefix_sum = [ 0 ] * n
prefix_sum[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
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 )
if num % 2 = = 0 :
current_sum * = - 1
if i = = j:
dp[i][num] = current_sum
else :
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)
{
int [, ] dp = new int [n, n + 1];
int [] prefixSum = new int [n];
prefixSum[0] = arr[0];
for ( int i = 1; i < n; i++) {
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);
if (num % 2 == 0) {
currentSum *= -1;
}
if (i == j) {
dp[i, num] = currentSum;
}
else {
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) {
const dp = new Array(n).fill(0).map(() => new Array(n).fill(0));
const prefixSum = new Array(n).fill(0);
prefixSum[0] = a[0];
for (let i = 1; i < n; i++) {
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);
if (num % 2 === 0) {
currentSum *= -1;
}
if (i === j) {
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
Maximum possible Array sum after performing given operations
Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer
9 min read
Maximum possible array sum after performing the given operation
Given an array arr[] of size N, the task is to find the maximum sum of the elements of the array after applying the given operation any number of times. In a single operation, choose an index 1 ? i < N and multiply both arr[i] and arr[i - 1] by -1.Examples: Input: arr[] = {-10, 5, -4} Output: 19
9 min read
Maximum Possible Product in Array after performing given Operations
Given an array with size N. You are allowed to perform two types of operations on the given array as described below: Choose some position i and j, such that (i is not equals to j), replace the value of a[j] with a[i]*a[j] and remove the number from the ith cell.Choose some position i and remove the
13 min read
Minimum possible sum of array elements after performing the given operation
Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
9 min read
Maximise minimum element possible in Array after performing given operations
Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. F
11 min read
Maximum sum of all elements of array after performing given operations
Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none
7 min read
Maximum sum possible from given Matrix by performing given operations
Given a matrix arr[][] of dimensions 2 * N, the task is to maximize the sum possible by selecting at most one element from each column such that no two consecutive elements are chosen from the same row. Examples: Input: arr[][] = {{1, 50, 21, 5}, {2, 10, 10, 5}}Output: 67Explanation: Elements arr[1]
11 min read
Maximum count of equal numbers in an array after performing given operations
Given an array of integers. The task is to find the maximum count of equal numbers in an array after applying the given operation any number of times. In an operation: Choose two elements of the array a[i], a[j] (such that i is not equals to j) and, Increase number a[i] by 1 and decrease number a[j]
5 min read
Find the Maximum sum of the Array by performing the given operations
Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
5 min read
Maximum possible sum after M operations on N cards
Given an array arr[] of size N which represents the initial number on each card and given a two dimensional array B[][] of size M where M represents the number of operations that need to be performed. At each operation, choose at most B[j][0] cards (possibly zero) and replace the integer written on
8 min read