Related Articles

Related Articles

Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence
  • Last Updated : 23 Oct, 2020

Given an array arr[] consisting of N positive integers, the task is to find the maximum sum of subsequence 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

5










 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :