Open In App

Find the Maximum Alternate Subsequence Sum from a given array

Given an array arr[] of size n having both positive and negative integer excluding zero. Find the maximum sum of maximum size alternate subsequence of a given sequence that is, in a subsequence sign of each adjacent element is opposite for example if the first one is positive then the second one has to be negative followed by another positive integer and so on.

Examples:



Input : arr[] = {1, 2, 3, 4, -1, -2} 
Output :
Explanation: 
Here, maximum size subsequences are [1, -1] [1, -2] [2, -1] [2, -2] [3, -1] 
[3, -2] [4, -1] [4, -2] but the subsequence which have maximum sum is [4, -1] 
and the sum of this subsequence is 3. Hence, the output is 3.

Input : arr[] = {-1, -6, 12, -4, -5} 
Output :
Explanation: 
Here, maximum size subsequences are [-1, 12, -4] [-1, 12, -5] [-6, -12, -4] 
[-6, 12, -5] but the subsequence which have maximum sum is [-1, 12, -4] 
and the sum of this subsequence is 7. Hence, the output is 7. 
 



Naive approach:
To solve the problem mentioned above the simple approach is to find all the alternating subsequences and their sum and return the maximum sum among all of them. 

Efficient Approach:
The efficient approach to solve the above problem is to pick the maximum element among continuous positive and continuous negative elements every time and add it to the maximum sum so far. The variable which stores the maximum sum will hold the final answer.

Below is the implementation of the above-mentioned approach: 




// C++ program to find the maximum
// alternating subsequence sum for
// a given array
#include <iostream>
using namespace std;
 
// Function to find maximum
// alternating subsequence sum
int maxAlternatingSum(int arr[], int n)
{
     
    // Initialize sum to 0
    int max_sum = 0;
    int i = 0;
      
    while (i < n)
    {
        int current_max = arr[i];
        int k = i;
          
         while (k < n &&
              ((arr[i] > 0 && arr[k] > 0) ||
               (arr[i] < 0 && arr[k] < 0)))
        {
            current_max = max(current_max, arr[k]);
            k += 1;
        }
          
        // Calculate the sum
        max_sum += current_max;
          
        i = k;
    }
      
    // Return the final result
    return max_sum;   
}
 
// Driver Code
int main()
{
     
    // Array initialization
    int arr[] = { 1, 2, 3, 4, -1, -2 };
      
    // Length of array
    int n = sizeof(arr) / sizeof(arr[0]);
     
    cout << maxAlternatingSum(arr, n);
    return 0;
}
 
// This code is contributed by avanitrachhadiya2155




// Java program to find the maximum
// alternating subsequence sum for
// a given array
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to find maximum
// alternating subsequence sum
static int maxAlternatingSum(int[] arr, int n)
{
     
    // Initialize sum to 0
    int max_sum = 0;
     
    int i = 0;
     
    while (i < n)
    {
        int current_max = arr[i];
        int k = i;
         
         while (k < n &&
              ((arr[i] > 0 && arr[k] > 0) ||
               (arr[i] < 0 && arr[k] < 0)))
         {
            current_max = Math.max(current_max, arr[k]);
            k += 1;
        }
         
        // Calculate the sum
        max_sum += current_max;
         
        i = k;
    }
     
    // Return the final result
    return max_sum;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Array initialization
    int[] arr = { 1, 2, 3, 4, -1, -2 };
     
    // Length of array
    int n = arr.length;
     
    System.out.println(maxAlternatingSum(arr, n));
}
}
 
// This code is contributed by offbeat




# Python3 program to find the maximum alternating
# subsequence sum for a given array
 
# Function to find maximum
# alternating subsequence sum
def maxAlternatingSum(arr, n):
 
    # initialize sum to 0
    max_sum = 0
     
    i = 0
     
    while i<n:
        current_max = arr[i]
        k = i
         
        while k<n and ((arr[i]>0 and arr[k]>0)
        or (arr[i]<0 and arr[k]<0)):
             
            current_max = max(current_max, arr[k])
             
            k+= 1
         
        # calculate the sum
        max_sum+= current_max
         
        i = k
         
    # return the final result
    return max_sum
 
 
# Driver code
 
# array initialization
arr = [1, 2, 3, 4, -1, -2]
 
# length of array
n = len(arr)
 
print(maxAlternatingSum(arr, n))




// C# program to find the maximum
// alternating subsequence sum for
// a given array
using System;
class GFG{
 
// Function to find maximum
// alternating subsequence sum
static int maxAlternatingSum(int[] arr,
                             int n)
{
  // Initialize sum to 0
  int max_sum = 0;
 
  int i = 0;
 
  while (i < n)
  {
    int current_max = arr[i];
    int k = i;
 
    while (k < n &&
          ((arr[i] > 0 && arr[k] > 0) ||
           (arr[i] < 0 && arr[k] < 0)))
    {
      current_max = Math.Max(current_max,
                             arr[k]);
      k += 1;
    }
 
    // Calculate the sum
    max_sum += current_max;
 
    i = k;
  }
 
  // Return the final result
  return max_sum;
}
 
// Driver Code
public static void Main()
{    
  // Array initialization
  int[] arr = {1, 2, 3, 4,
               -1, -2};
 
  // Length of array
  int n = arr.Length;
 
  Console.Write(maxAlternatingSum(arr, n));
}
}
 
// This code is contributed by Chitranayal




<script>
// JS program to find the maximum
// alternating subsequence sum for
// a given array
 
 
// Function to find maximum
// alternating subsequence sum
function maxAlternatingSum( arr, n)
{
     
    // Initialize sum to 0
    var max_sum = 0;
     
    var i = 0;
     
    while (i < n)
    {
        var current_max = arr[i];
        var k = i;
         
        while (k < n &&
            ((arr[i] > 0 && arr[k] > 0) ||
            (arr[i] < 0 && arr[k] < 0)))
        {
            current_max = Math.max(current_max, arr[k]);
            k += 1;
        }
         
        // Calculate the sum
        max_sum += current_max;
         
        i = k;
    }
     
    // Return the final result
    return max_sum;
}
 
// Driver Code
 
    // Array initialization
    var arr = [ 1, 2, 3, 4, -1, -2 ];
     
    // Length of array
    var n = arr.length;
     
    document.write(maxAlternatingSum(arr, n));
 
 
 
 
</script>

Output: 
3

 

Time Complexity: O(n)
Auxiliary Space: O(1)


Article Tags :