Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum length Subsequence with alternating sign and maximum Sum
Next article icon

Maximum length Subsequence with alternating sign and maximum Sum

Last Updated : 28 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n having both positive and negative integer excluding zero. The task is to find the subsequence with an alternating sign having maximum size and maximum sum 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[] = {2, 3, 7, -6, -4} Output: 7 -4 Explanation: Possible subsequences are [2, -6] [2, -4] [3, -6] [3, -4] [7, -6] [7, -4]. Out of these [7, -4] has the maximum sum.   Input: arr[] = {-4, 9, 4, 11, -5, -17, 9, -3, -5, 2} Output: -4 11 -5 9 -3 2  


 


Approach: 
The main idea to solve the above problem is to find the maximum element from the segments of the array which consists of the same sign which means we have to pick the maximum element among continuous positive and continuous negative elements. As we want maximum size we will only take one element from each segment and also to maximize the sum, we need to take the maximum element of each segment. 
Below is the implementation of the above approach: 
 

CPP
// C++ implementation to find the // subsequence with alternating sign // having maximum size and maximum sum.  #include <bits/stdc++.h> using namespace std;  // Function to find the subsequence // with alternating sign having // maximum size and maximum sum. void findSubsequence(int arr[], int n) {     int sign[n] = { 0 };      // Find whether each element     // is positive or negative     for (int i = 0; i < n; i++) {         if (arr[i] > 0)             sign[i] = 1;         else             sign[i] = -1;     }      int k = 0;     int result[n] = { 0 };      // Find the required subsequence     for (int i = 0; i < n; i++) {          int cur = arr[i];         int j = i;          while (j < n && sign[i] == sign[j]) {              // Find the maximum element             // in the specified range             cur = max(cur, arr[j]);             ++j;         }          result[k++] = cur;          i = j - 1;     }      // print the result     for (int i = 0; i < k; i++)         cout << result[i] << " ";     cout << "\n"; }  // Driver code int main() {     // array declaration     int arr[] = { -4, 9, 4, 11, -5, -17, 9, -3, -5, 2 };      // size of array     int n = sizeof(arr) / sizeof(arr[0]);      findSubsequence(arr, n);      return 0; } 
Java
// Java implementation to find the // subsequence with alternating sign // having maximum size and maximum sum. class GFG{   // Function to find the subsequence // with alternating sign having // maximum size and maximum sum. static void findSubsequence(int arr[], int n) {     int sign[] = new int[n];       // Find whether each element     // is positive or negative     for (int i = 0; i < n; i++) {         if (arr[i] > 0)             sign[i] = 1;         else             sign[i] = -1;     }       int k = 0;     int result[] = new int[n];       // Find the required subsequence     for (int i = 0; i < n; i++) {           int cur = arr[i];         int j = i;           while (j < n && sign[i] == sign[j]) {               // Find the maximum element             // in the specified range             cur = Math.max(cur, arr[j]);             ++j;         }           result[k++] = cur;           i = j - 1;     }       // print the result     for (int i = 0; i < k; i++)         System.out.print(result[i]+ " ");     System.out.print("\n"); }   // Driver code public static void main(String[] args) {     // array declaration     int arr[] = { -4, 9, 4, 11, -5, -17, 9, -3, -5, 2 };       // size of array     int n = arr.length;       findSubsequence(arr, n); } }  // This code is contributed by Princi Singh 
Python3
# Python3 implementation to find the # subsequence with alternating sign # having maximum size and maximum sum.  # Function to find the subsequence # with alternating sign having # maximum size and maximum sum. def findSubsequence(arr, n):     sign = [0]*n      # Find whether each element     # is positive or negative     for i in range(n):         if (arr[i] > 0):             sign[i] = 1         else:             sign[i] = -1      k = 0     result = [0]*n      # Find the required subsequence     i = 0     while i < n:          cur = arr[i]         j = i          while (j < n and sign[i] == sign[j]):              # Find the maximum element             # in the specified range             cur = max(cur, arr[j])             j += 1          result[k] = cur         k += 1          i = j - 1         i += 1      # print the result     for i in range(k):         print(result[i],end=" ")  # Driver code if __name__ == '__main__':     # array declaration     arr=[-4, 9, 4, 11, -5, -17, 9, -3, -5, 2]      # size of array     n = len(arr)      findSubsequence(arr, n)  # This code is contributed by mohit kumar 29 
C#
// C# implementation to find the // subsequence with alternating sign // having maximum size and maximum sum. using System;  public class GFG{    // Function to find the subsequence // with alternating sign having // maximum size and maximum sum. static void findSubsequence(int []arr, int n) {     int []sign = new int[n];        // Find whether each element     // is positive or negative     for (int i = 0; i < n; i++) {         if (arr[i] > 0)             sign[i] = 1;         else             sign[i] = -1;     }        int k = 0;     int []result = new int[n];        // Find the required subsequence     for (int i = 0; i < n; i++) {            int cur = arr[i];         int j = i;            while (j < n && sign[i] == sign[j]) {                // Find the maximum element             // in the specified range             cur = Math.Max(cur, arr[j]);             ++j;         }            result[k++] = cur;            i = j - 1;     }        // print the result     for (int i = 0; i < k; i++)         Console.Write(result[i]+ " ");     Console.Write("\n"); }    // Driver code public static void Main(String[] args) {     // array declaration     int []arr = { -4, 9, 4, 11, -5, -17, 9, -3, -5, 2 };        // size of array     int n = arr.Length;        findSubsequence(arr, n); } } // This code contributed by Rajput-Ji 
JavaScript
<script>  // Javascript implementation to find the // subsequence with alternating sign // having maximum size and maximum sum.  // Function to find the subsequence // with alternating sign having // maximum size and maximum sum. function findSubsequence(arr, n) {     let sign = Array.from({length: n}, (_, i) => 0);         // Find whether each element     // is positive or negative     for (let i = 0; i < n; i++)     {         if (arr[i] > 0)             sign[i] = 1;         else             sign[i] = -1;     }         let k = 0;     let result = Array.from({length: n}, (_, i) => 0);         // Find the required subsequence     for (let i = 0; i < n; i++) {             let cur = arr[i];         let j = i;             while (j < n && sign[i] == sign[j]) {                 // Find the maximum element             // in the specified range             cur = Math.max(cur, arr[j]);             ++j;         }             result[k++] = cur;             i = j - 1;     }         // print the result     for (let i = 0; i < k; i++)         document.write(result[i]+ " ");     document.write("<br/>"); }  // Driver Code          // array declaration     let arr = [ -4, 9, 4, 11, -5, -17, 9, -3, -5, 2 ];         // size of array     let n = arr.length;         findSubsequence(arr, n);  // This code is contributed by sanjoy_62. </script> 

Output: 
-4 11 -5 9 -3 2

 

Time Complexity :O(N)

Auxiliary Space: O(N)
 


Next Article
Maximum length Subsequence with alternating sign and maximum Sum

E

epistler_999
Improve
Article Tags :
  • Algorithms
  • Analysis of Algorithms
  • Mathematical
  • Technical Scripter
  • Competitive Programming
  • Programming Language
  • Write From Home
  • DSA
  • Arrays
  • subsequence
Practice Tags :
  • Algorithms
  • Arrays
  • Mathematical

Similar Reads

    Longest alternating subsequence with maximum sum | Set 2
    Given an array arr[] of size N, consisting of positive and negative integers, the task is to find the longest alternating subsequence(i.e. the sign of every element is opposite to that of its previous element) from the given array which has the maximum sum.Examples: Input: arr[] = {-2, 10, 3, -8, -4
    7 min read
    Longest alternating subsequence which has maximum sum of elements
    Given a list of length N with positive and negative integers. The task is to choose the longest alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite of the sign of the current element). Among all such subsequences, we have to choose one which has the maxi
    10 min read
    Maximum sum alternating subsequence
    Given an array, the task is to find sum of maximum sum alternating subsequence starting with first element. Here alternating sequence means first decreasing, then increasing, then decreasing, ... For example 10, 5, 14, 3 is an alternating sequence. Note that the reverse type of sequence (increasing
    13 min read
    Maximum sum subsequence of any size which is decreasing-increasing alternatively
    Given an array of integers arr[], find the subsequence with maximum sum whose elements are first decreasing, then increasing, or vice versa, The subsequence can start anywhere in the main sequence, not necessarily at the first element of the main sequence. A sequence {x1, x2, .. xn} is an alternatin
    15+ min read
    Maximum sum subsequence with at-least k distant elements
    Given an array and a number k, find a subsequence such that Sum of elements in subsequence is maximumIndices of elements of subsequence differ atleast by k Examples Input : arr[] = {4, 5, 8, 7, 5, 4, 3, 4, 6, 5} k = 2 Output: 19 Explanation: The highest value is obtained if you pick indices 1, 4, 7,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences