Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence
Last Updated :
13 Apr, 2023
Given an array arr[] consisting of N positive integers, the task is to find the maximum sum of subsequences from the given array such that elements in the subsequence are assigned positive and negative signs alternately.
Subsequence = {a, b, c, d, e, … },
Sum of the above subsequence = (a – b + c – d + e – …)
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
The subsequence having maximum sum is {4}.
The sum is 4.
Input: arr[]= {1, 2, 3, 4, 1, 2 }
Output: 5
Explanation:
The subsequence having maximum sum is {4, 1, 2}.
The sum = 4 -1 + 2 = 5.
Naive Approach: The simplest approach is to generate all the subsequences of the given array and then find the sum for every subsequence and print the maximum among all the sum of the subsequences.
Time Complexity: O(N*2N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Initialize an auxiliary space dp[][] of size N*2 to store the Overlapping Subproblems. In each recursive call, add arr[i] or (-1)*arr[i] to the sum with the respective flag variable that denotes whether the current element is positive or negative. Below are the steps:
- Create a 2D dp[][] array of size N*2 and initialize the array with the -1.
- Pass the variable flag that denotes the sign of the element have to pick in the next term. For Example, in the subsequence, {a, b, c}, then the maximum subsequence can be (a – b + c) or (b – c) or c. Instead of recurring for all the Overlapping Subproblems, again and again, store once in dp[][] array and use the recurring state.
- If the flag is 0 then the current element is to be considered as a positive element and if the flag is 1 then the current element is to be considered as a negative element.
- Store every result into the dp[][] array.
- Print the value of dp[N][flag] as the maximum sum after the above steps.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMax(vector< int >& a, int dp[][2],
int i, int flag)
{
if (i == ( int )a.size()) {
return 0;
}
if (dp[i][flag] != -1) {
return dp[i][flag];
}
int ans;
if (flag == 0) {
ans = max(findMax(a, dp, i + 1, 0),
a[i]
+ findMax(a, dp,
i + 1, 1));
}
else {
ans = max(findMax(a, dp, i + 1, 1),
-1 * a[i]
+ findMax(a, dp,
i + 1, 0));
}
return dp[i][flag] = ans;
}
void findMaxSumUtil(vector< int >& arr,
int N)
{
int dp[N][2];
memset (dp, -1, sizeof dp);
cout << findMax(arr, dp, 0, 0);
}
int main()
{
vector< int > arr = { 1, 2, 3, 4, 1, 2 };
int N = arr.size();
findMaxSumUtil(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG{
static int findMax( int [] a, int dp[][],
int i, int flag)
{
if (i == ( int )a.length)
{
return 0 ;
}
if (dp[i][flag] != - 1 )
{
return dp[i][flag];
}
int ans;
if (flag == 0 )
{
ans = Math.max(findMax(a, dp, i + 1 , 0 ),
a[i] + findMax(a, dp, i + 1 , 1 ));
}
else
{
ans = Math.max(findMax(a, dp, i + 1 , 1 ),
- 1 * a[i] + findMax(a, dp, i + 1 , 0 ));
}
return dp[i][flag] = ans;
}
static void findMaxSumUtil( int [] arr,
int N)
{
int dp[][] = new int [N][ 2 ];
for ( int i = 0 ; i < N; i++)
{
for ( int j = 0 ; j < 2 ; j++)
{
dp[i][j] = - 1 ;
}
}
System.out.println(findMax(arr, dp, 0 , 0 ));
}
public static void main (String[] args)
{
int [] arr = { 1 , 2 , 3 , 4 , 1 , 2 };
int N = arr.length;
findMaxSumUtil(arr, N);
}
}
|
Python3
def findMax(a, dp, i, flag):
if (i = = len (a)):
return 0
if (dp[i][flag] ! = - 1 ):
return dp[i][flag]
ans = 0
if (flag = = 0 ):
ans = max (findMax(a, dp, i + 1 , 0 ),
a[i] + findMax(a, dp, i + 1 , 1 ))
else :
ans = max (findMax(a, dp, i + 1 , 1 ),
- 1 * a[i] + findMax(a, dp, i + 1 , 0 ))
dp[i][flag] = ans
return ans
def findMaxSumUtil(arr, N):
dp = [[ - 1 for i in range ( 2 )]
for i in range (N)]
print (findMax(arr, dp, 0 , 0 ))
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 , 1 , 2 ]
N = len (arr)
findMaxSumUtil(arr, N)
|
C#
using System;
class GFG {
static int findMax( int [] a, int [,] dp,
int i, int flag)
{
if (i == ( int )a.Length)
{
return 0;
}
if (dp[i, flag] != -1)
{
return dp[i, flag];
}
int ans;
if (flag == 0)
{
ans = Math.Max(findMax(a, dp, i + 1, 0),
a[i] + findMax(a, dp, i + 1, 1));
}
else
{
ans = Math.Max(findMax(a, dp, i + 1, 1),
-1 * a[i] + findMax(a, dp, i + 1, 0));
}
return dp[i, flag] = ans;
}
static void findMaxSumUtil( int [] arr,
int N)
{
int [,] dp = new int [N, 2];
for ( int i = 0; i < N; i++)
{
for ( int j = 0; j < 2; j++)
{
dp[i, j] = -1;
}
}
Console.WriteLine(findMax(arr, dp, 0, 0));
}
public static void Main()
{
int [] arr = { 1, 2, 3, 4, 1, 2 };
int N = arr.Length;
findMaxSumUtil(arr, N);
}
}
|
Javascript
<script>
function findMax(a, dp, i, flag)
{
if (i == a.length)
{
return 0;
}
if (dp[i][flag] != -1)
{
return dp[i][flag];
}
let ans;
if (flag == 0)
{
ans = Math.max(findMax(a, dp, i + 1, 0),
a[i] + findMax(a, dp, i + 1, 1));
}
else
{
ans = Math.max(findMax(a, dp, i + 1, 1),
-1 * a[i] + findMax(a, dp, i + 1, 0));
}
return dp[i][flag] = ans;
}
function findMaxSumUtil(arr, N)
{
let dp = new Array(N);
for ( var i = 0; i < dp.length; i++)
{
dp[i] = new Array(2);
}
for (let i = 0; i < N; i++)
{
for (let j = 0; j < 2; j++)
{
dp[i][j] = -1;
}
}
document.write(findMax(arr, dp, 0, 0));
}
let arr = [ 1, 2, 3, 4, 1, 2 ];
let N = arr.length;
findMaxSumUtil(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: Using the DP Tabulation method ( Iterative approach )
The approach to solving this problem is the same but the DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because the memoization method needs extra stack space for recursion calls.
Steps to solve this problem :
- Create a table DP to store the solution of the subproblems.
- Initialize the table with base cases
- Now Iterate over subproblems to get the value of the current problem from the previous computation of subproblems stored in DP.
- Return the final solution stored in dp[0]0].
Implementation :
C++
#include <bits/stdc++.h>
using namespace std;
int findMax(vector< int >& a, int N)
{
int dp[N][2];
dp[N-1][0] = a[N-1];
dp[N-1][1] = 0;
for ( int i = N-2; i >= 0; i--) {
dp[i][0] = max(dp[i+1][0], a[i]+dp[i+1][1]);
dp[i][1] = max(dp[i+1][1], -1*a[i]+dp[i+1][0]);
}
return dp[0][0];
}
int main()
{
vector< int > arr = { 1, 2, 3, 4, 1, 2 };
int N = arr.size();
cout << findMax(arr, N);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int findMax(List<Integer> a, int N) {
int [][] dp = new int [N][ 2 ];
dp[N- 1 ][ 0 ] = a.get(N- 1 );
dp[N- 1 ][ 1 ] = 0 ;
for ( int i = N- 2 ; i >= 0 ; i--) {
dp[i][ 0 ] = Math.max(dp[i+ 1 ][ 0 ], a.get(i)+dp[i+ 1 ][ 1 ]);
dp[i][ 1 ] = Math.max(dp[i+ 1 ][ 1 ], - 1 *a.get(i)+dp[i+ 1 ][ 0 ]);
}
return dp[ 0 ][ 0 ];
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>(Arrays.asList( 1 , 2 , 3 , 4 , 1 , 2 ));
int N = arr.size();
System.out.println(findMax(arr, N));
}
}
|
Python3
def findMax(a, N):
dp = [[ 0 for i in range ( 2 )] for j in range (N)]
dp[N - 1 ][ 0 ] = a[N - 1 ]
dp[N - 1 ][ 1 ] = 0
for i in range (N - 2 , - 1 , - 1 ):
dp[i][ 0 ] = max (dp[i + 1 ][ 0 ], a[i] + dp[i + 1 ][ 1 ])
dp[i][ 1 ] = max (dp[i + 1 ][ 1 ], - 1 * a[i] + dp[i + 1 ][ 0 ])
return dp[ 0 ][ 0 ]
arr = [ 1 , 2 , 3 , 4 , 1 , 2 ]
N = len (arr)
print (findMax(arr, N))
|
C#
using System;
class MaxSumSubsequence {
static int findMax( int [] a, int N)
{
int [, ] dp = new int [N, 2];
dp[N - 1, 0] = a[N - 1];
dp[N - 1, 1] = 0;
for ( int i = N - 2; i >= 0; i--) {
dp[i, 0] = Math.Max(dp[i + 1, 0],
a[i] + dp[i + 1, 1]);
dp[i, 1] = Math.Max(dp[i + 1, 1],
-1 * a[i] + dp[i + 1, 0]);
}
return dp[0, 0];
}
static void Main()
{
int [] arr = { 1, 2, 3, 4, 1, 2 };
int N = arr.Length;
Console.WriteLine(findMax(arr, N));
}
}
|
Javascript
function findMax(arr, N) {
let dp = new Array(N);
for (let i = 0; i < N; i++) {
dp[i] = new Array(2);
}
dp[N - 1][0] = arr[N - 1];
dp[N - 1][1] = 0;
for (let i = N - 2; i >= 0; i--) {
dp[i][0] = Math.max(dp[i + 1][0], arr[i] + dp[i + 1][1]);
dp[i][1] = Math.max(dp[i + 1][1], -1 * arr[i] + dp[i + 1][0]);
}
return dp[0][0];
}
let arr = [1, 2, 3, 4, 1, 2];
let N = arr.length;
console.log(findMax(arr, N));
|
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...