Open In App

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

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 subsequence
int 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 signs
void 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 Code
int 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 approach
import java.io.*;
import java.util.Arrays;
 
class GFG{
  
// Function to find the
// maximum sum subsequence
static 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 signs
static 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 Code
public 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 subsequence
def 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 signs
def 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 Code
if __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 approach
using System;
 
class GFG {
  
// Function to find the
// maximum sum subsequence
static 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 signs
static 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 subsequence
function 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 signs
function 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 call
findMaxSumUtil(arr, N);
 
// This code is contributed by splevel62
 
</script>


Output: 

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 subsequence
int 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 Code
int 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 element
def 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 Code
arr = [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 Code
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
Previous
Next
Share your thoughts in the comments

Similar Reads