Longest subsequence having maximum sum - GeeksforGeeks

21 Apr, 2021
Given an array arr[] of size N, the task is to find the longest non-empty subsequence from the given array whose sum is maximum.
Examples:
Input: arr[] = { 1, 2, -4, -2, 3, 0 } Output: 1 2 3 0 Explanation: Sum of elements of the subsequence {1, 2, 3, 0} is 6 which is the maximum possible sum. Therefore, the required output is 1 2 3 0
Input: arr[] = { -10, -6, -2, -3, -4 } Output: -2
Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subsequence of the given array and calculate their sums. Print the longest of all subsequences with maximum sum. 
Time Complexity: O(N * 2N) Auxiliary Space: O(N)
Efficient Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:
Initialize a variable, say maxm, to store the largest element of the given array.
If maxm < 0, then print the value of maxm.
Otherwise, traverse the array and print all positive array elements.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest subsequence// from the given array with maximum sumvoid longestSubWithMaxSum(int arr[], int N){    // Stores the largest element    // of the array    int Max = *max_element(arr,                           arr + N);     // If Max is less than 0    if (Max < 0) {         // Print the largest element        // of the array        cout << Max;        return;    }     // Traverse the array    for (int i = 0; i < N; i++) {         // If arr[i] is greater        // than or equal to 0        if (arr[i] >= 0) {             // Print elements of            // the subsequence            cout << arr[i] << " ";        }    }} // Driver Codeint main(){    int arr[] = { 1, 2, -4, -2, 3, 0 };     int N = sizeof(arr) / sizeof(arr[0]);     longestSubWithMaxSum(arr, N);    return 0;}
// Java program to implement// the above approachimport java.util.*;  class GFG{  // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int arr[], int N){         // Stores the largest element    // of the array    int Max = Arrays.stream(arr).max().getAsInt();      // If Max is less than 0    if (Max < 0)    {                 // Print the largest element        // of the array        System.out.print(Max);        return;    }      // Traverse the array    for(int i = 0; i < N; i++)    {                 // If arr[i] is greater        // than or equal to 0        if (arr[i] >= 0)        {                         // Print elements of            // the subsequence            System.out.print(arr[i] + " ");        }    }}  // Driver Codepublic static void main(String[] args){    int arr[] = { 1, 2, -4, -2, 3, 0 };    int N = arr.length;      longestSubWithMaxSum(arr, N);}} // This code is contributed by code_hunt
# Python3 program to implement# the above approach # Function to find the longest subsequence# from the given array with maximum sumdef longestSubWithMaxSum(arr, N):     # Stores the largest element    # of the array    Max = max(arr)     # If Max is less than 0    if (Max < 0) :         # Print the largest element        # of the array        print(Max)        return     # Traverse the array    for i in range(N):         # If arr[i] is greater        # than or equal to 0        if (arr[i] >= 0) :             # Print elements of            # the subsequence            print(arr[i], end = " ") # Driver codearr = [ 1, 2, -4, -2, 3, 0 ] N = len(arr) longestSubWithMaxSum(arr, N) # This code is contributed divyeshrabadiya07
// C# program to implement// the above approachusing System; class GFG{  // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int []arr,                                 int N){         // Stores the largest element    // of the array    int Max = arr[0];         for(int i = 1; i < N; i++)    {        if (Max < arr[i])            Max = arr[i];    }         // If Max is less than 0    if (Max < 0)    {                 // Print the largest element        // of the array        Console.Write(Max);        return;    }         // Traverse the array    for(int i = 0; i < N; i++)    {                 // If arr[i] is greater        // than or equal to 0        if (arr[i] >= 0)        {                         // Print elements of            // the subsequence            Console.Write(arr[i] + " ");        }    }}  // Driver Codepublic static void Main(String[] args){    int []arr = { 1, 2, -4, -2, 3, 0 };    int N = arr.Length;      longestSubWithMaxSum(arr, N);}} // This code is contributed by aashish1995
<script> // JavaScript program to implement// the above approach // Function to find the longest subsequence// from the given array with maximum sumfunction longestSubWithMaxSum(arr, N){             // Stores the largest element    // of the array    let Max = Math.max(...arr);       // If Max is less than 0    if (Max < 0)    {                  // Print the largest element        // of the array        document.write(Max);        return;    }       // Traverse the array    for(let i = 0; i < N; i++)    {                  // If arr[i] is greater        // than or equal to 0        if (arr[i] >= 0)        {                          // Print the elements of            // the subsequence            document.write(arr[i] + " ");        }    }}  // Driver codelet arr = [ 1, 2, -4, -2, 3, 0 ];let N = arr.length; longestSubWithMaxSum(arr, N); // This code is contributed by avijitmondal1998 </script>
1 2 3 0
 
Time Complexity: O(N) Auxiliary Space: O(1)
code_hunt
divyeshrabadiya07
aashish1995
avijitmondal1998
interview-preparation
subsequence
Arrays
Greedy
Mathematical
Searching
Arrays
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string