Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence

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++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the// maximum sum subsequenceint findMax(vector<int>& a, int dp[][2],            int i, int flag){    // Base Case    if (i == (int)a.size()) {        return 0;    }Â
    // If current state is already    // calculated then use it    if (dp[i][flag] != -1) {        return dp[i][flag];    }Â
    int ans;Â
    // If current element is positive    if (flag == 0) {Â
        // Update ans and recursively        // call with update value of flag        ans = max(findMax(a, dp, i + 1, 0),                  a[i]                      + findMax(a, dp,                                i + 1, 1));    }Â
    // Else current element is negative    else {Â
        // Update ans and recursively        // call with update value of flag        ans = max(findMax(a, dp, i + 1, 1),                  -1 * a[i]                      + findMax(a, dp,                                i + 1, 0));    }Â
    // Return maximum sum subsequence    return dp[i][flag] = ans;}Â
// Function that finds the maximum// sum of element of the subsequence// with alternate +ve and -ve signsvoid findMaxSumUtil(vector<int>& arr,                    int N){    // Create auxiliary array dp[][]    int dp[N][2];Â
    // Initialize dp[][]    memset(dp, -1, sizeof dp);Â
    // Function Call    cout << findMax(arr, dp, 0, 0);}Â
// Driver Codeint main(){Â Â Â Â // Given array arr[]Â Â Â Â vector<int> arr = { 1, 2, 3, 4, 1, 2 };Â
    int N = arr.size();Â
    // Function Call    findMaxSumUtil(arr, N);Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.util.Arrays; Â
class GFG{  // Function to find the// maximum sum subsequencestatic int findMax(int[] a, int dp[][],                   int i, int flag){         // Base Case    if (i == (int)a.length)    {        return 0;    }      // If current state is already    // calculated then use it    if (dp[i][flag] != -1)    {        return dp[i][flag];    }      int ans;      // If current element is positive    if (flag == 0)    {                 // Update ans and recursively        // call with update value of flag        ans = Math.max(findMax(a, dp, i + 1, 0),                 a[i] + findMax(a, dp, i + 1, 1));    }      // Else current element is negative    else    {                 // Update ans and recursively        // call with update value of flag        ans = Math.max(findMax(a, dp, i + 1, 1),            -1 * a[i] + findMax(a, dp, i + 1, 0));    }      // Return maximum sum subsequence    return dp[i][flag] = ans;}  // Function that finds the maximum// sum of element of the subsequence// with alternate +ve and -ve signsstatic void findMaxSumUtil(int[] arr,                           int N){         // Create auxiliary array dp[][]    int dp[][] = new int[N][2];      // Initialize dp[][]    for(int i = 0; i < N; i++)    {        for(int j = 0; j < 2; j++)        {            dp[i][j] = -1;        }    }         // Function Call    System.out.println(findMax(arr, dp, 0, 0));}  // Driver Codepublic static void main (String[] args){         // Given array arr[]    int[] arr = { 1, 2, 3, 4, 1, 2 };      int N = arr.length;      // Function call    findMaxSumUtil(arr, N);}}Â
// This code is contributed by sanjoy_62 |
Python3
# Python3 program for the above approachÂ
# Function to find the# maximum sum subsequencedef findMax(a, dp, i, flag):         # Base Case    if (i == len(a)):        return 0Â
    # If current state is already    # calculated then use it    if (dp[i][flag] != -1):        return dp[i][flag]Â
    ans = 0Â
    # If current element is positive    if (flag == 0):Â
        # Update ans and recursively        # call with update value of flag        ans = max(findMax(a, dp, i + 1, 0),           a[i] + findMax(a, dp, i + 1, 1))Â
    # Else current element is negative    else:Â
        # Update ans and recursively        # call with update value of flag        ans = max(findMax(a, dp, i + 1, 1),       -1 * a[i] + findMax(a, dp, i + 1, 0))Â
    # Return maximum sum subsequence    dp[i][flag] = ans         return ansÂ
# Function that finds the maximum# sum of element of the subsequence# with alternate +ve and -ve signsdef findMaxSumUtil(arr, N):Â Â Â Â Â Â Â Â Â # Create auxiliary array dp[][]Â Â Â Â dp = [[-1 for i in range(2)] Â Â Â Â Â Â Â Â Â Â Â Â Â Â for i in range(N)]Â
    # Function call    print(findMax(arr, dp, 0, 0))Â
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â # Given array arr[]Â Â Â Â arr = [ 1, 2, 3, 4, 1, 2 ]Â
    N = len(arr)Â
    # Function call    findMaxSumUtil(arr, N)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;Â
class GFG {   // Function to find the// maximum sum subsequencestatic int findMax(int[] a, int[,] dp,                   int i, int flag){         // Base Case    if (i == (int)a.Length)    {        return 0;    }       // If current state is already    // calculated then use it    if (dp[i, flag] != -1)    {        return dp[i, flag];    }       int ans;       // If current element is positive    if (flag == 0)    {                 // Update ans and recursively        // call with update value of flag        ans = Math.Max(findMax(a, dp, i + 1, 0),                 a[i] + findMax(a, dp, i + 1, 1));    }       // Else current element is negative    else    {                 // Update ans and recursively        // call with update value of flag        ans = Math.Max(findMax(a, dp, i + 1, 1),            -1 * a[i] + findMax(a, dp, i + 1, 0));    }       // Return maximum sum subsequence    return dp[i, flag] = ans;}   // Function that finds the maximum// sum of element of the subsequence// with alternate +ve and -ve signsstatic void findMaxSumUtil(int[] arr,                           int N){          // Create auxiliary array dp[][]    int[,] dp = new int[N, 2];       // Initialize dp[][]    for(int i = 0; i < N; i++)    {        for(int j = 0; j < 2; j++)        {            dp[i, j] = -1;        }    }          // Function Call    Console.WriteLine(findMax(arr, dp, 0, 0));}  // Driver Code public static void Main() {          // Given array arr[]    int[] arr = { 1, 2, 3, 4, 1, 2 };       int N = arr.Length;       // Function call    findMaxSumUtil(arr, N); } }Â
// This code is contributed by code_hunt |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the// maximum sum subsequencefunction findMax(a, dp, i, flag){         // Base Case    if (i == a.length)    {        return 0;    }       // If current state is already    // calculated then use it    if (dp[i][flag] != -1)    {        return dp[i][flag];    }       let ans;       // If current element is positive    if (flag == 0)    {                  // Update ans and recursively        // call with update value of flag        ans = Math.max(findMax(a, dp, i + 1, 0),                a[i] + findMax(a, dp, i + 1, 1));    }       // Else current element is negative    else    {                 // Update ans and recursively        // call with update value of flag        ans = Math.max(findMax(a, dp, i + 1, 1),           -1 * a[i] + findMax(a, dp, i + 1, 0));    }       // Return maximum sum subsequence    return dp[i][flag] = ans;}   // Function that finds the maximum// sum of element of the subsequence// with alternate +ve and -ve signsfunction findMaxSumUtil(arr, N){         // Create auxiliary array dp[][]    let dp = new Array(N);         // Loop to create 2D array using 1D array    for(var i = 0; i < dp.length; i++)     {        dp[i] = new Array(2);    }       // Initialize dp[][]    for(let i = 0; i < N; i++)    {        for(let j = 0; j < 2; j++)        {            dp[i][j] = -1;        }    }         // Function Call    document.write(findMax(arr, dp, 0, 0));}Â
// Driver codeÂ
// Given array arr[]let arr = [ 1, 2, 3, 4, 1, 2 ];Â
let N = arr.length;Â
// Function callfindMaxSumUtil(arr, N);Â
// This code is contributed by splevel62Â
</script> |
5
Â
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++
// C++ program for above approachÂ
#include <bits/stdc++.h>using namespace std;Â
Â
// Function to find the// maximum sum subsequenceint findMax(vector<int>& a, int N){Â Â Â Â int dp[N][2];Â
    // Initializing the base case    dp[N-1][0] = a[N-1];    dp[N-1][1] = 0;              // iterate over subproblems to get the current value     // from previous computation stored in DP    for (int i = N-2; i >= 0; i--) {                 // Update current value in DP        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 ans    return dp[0][0];}Â
// Driver Codeint main(){    vector<int> arr = { 1, 2, 3, 4, 1, 2 };    int N = arr.size();         // function Call    cout << findMax(arr, N);    return 0;}Â
// this code is contributed by bhardwajji |
Java
import java.util.*;Â
public class Main {    // Function to find the maximum sum subsequence    public static int findMax(List<Integer> a, int N) {        int[][] dp = new int[N][2];                 // Initializing the base case        dp[N-1][0] = a.get(N-1);        dp[N-1][1] = 0;                   // iterate over subproblems to get the current value         // from previous computation stored in DP        for (int i = N-2; i >= 0; i--) {            // Update current value in DP            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 ans        return dp[0][0];    }           // Driver Code    public static void main(String[] args) {        List<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 2));        int N = arr.size();                   // function Call        System.out.println(findMax(arr, N));    }} |
Python3
# Python program for the above approachÂ
# Function to find the maximum elementdef findMax(a, N):Â Â Â Â dp = [[0 for i in range(2)] for j in range(N)]Â
    # Initializing the base case    dp[N-1][0] = a[N-1]    dp[N-1][1] = 0Â
    # Iterate over subproblems to get the    # current value from previous computation    # stored in DP    for i in range(N-2, -1, -1):Â
        # Update current value in DP        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 ans    return dp[0][0]Â
Â
# Driver Codearr = [1, 2, 3, 4, 1, 2]N = len(arr)Â
print(findMax(arr, N)) |
C#
using System;Â
class MaxSumSubsequence {Â
    // Function to find the maximum sum    // of the subsequence    static int findMax(int[] a, int N)    {        int[, ] dp = new int[N, 2];Â
        // Initializing the base case        dp[N - 1, 0] = a[N - 1];        dp[N - 1, 1] = 0;Â
        // iterate over subproblems to get        // the current value from previous        // computation stored in DP        for (int i = N - 2; i >= 0; i--) {Â
            // Update current value in DP            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 the ans        return dp[0, 0];    }Â
    // Driver Code    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);Â Â }Â
  // Initializing the base case  dp[N - 1][0] = arr[N - 1];  dp[N - 1][1] = 0;Â
  // iterate over subproblems to get  // the current value from previous  // computation stored in DP  for (let i = N - 2; i >= 0; i--) {    // Update current value in DP    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 the ans  return dp[0][0];}Â
// Driver Codelet 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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



