Longest subsequence having maximum sum
Last Updated :
02 Mar, 2023
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:
Below is the implementation of the above approach:
C++
// 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 sum
void 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 Code
int main()
{
int arr[] = { 1, 2, -4, -2, 3, 0 };
int N = sizeof(arr) / sizeof(arr[0]);
longestSubWithMaxSum(arr, N);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to find the longest subsequence
// from the given array with maximum sum
static 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 Code
public 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
# Python3 program to implement
# the above approach
# Function to find the longest subsequence
# from the given array with maximum sum
def 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 code
arr = [ 1, 2, -4, -2, 3, 0 ]
N = len(arr)
longestSubWithMaxSum(arr, N)
# This code is contributed divyeshrabadiya07
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to find the longest subsequence
// from the given array with maximum sum
static 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 Code
public 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
JavaScript
<script>
// JavaScript program to implement
// the above approach
// Function to find the longest subsequence
// from the given array with maximum sum
function 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 code
let arr = [ 1, 2, -4, -2, 3, 0 ];
let N = arr.length;
longestSubWithMaxSum(arr, N);
// This code is contributed by avijitmondal1998
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
The AllPossible Subsequence Generator And Checking Way :
C++
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
void the_allpossible_getter(vector<vector<int>>&allsub,vector<int>&v,vector<int>&res,
int n,int index){
if(index>=n){
allsub.push_back(res);
return;
}
res.push_back(v[index]);
index+=1;
the_allpossible_getter(allsub,v,res,n,index);
index+=1;
res.pop_back();
the_allpossible_getter(allsub,v,res,n,index);
}
signed main(){
vector<int>v{ 1, 2, -4, -2, 3, 0 };
int n=6;
vector<int>res;
vector<vector<int>>allsub;
the_allpossible_getter(allsub,v,res,n,0);
res.clear();
int maxsum=INT_MIN;
for(auto it:allsub){
int sum=0;
vector<int>dump;
for(auto vt:it){
sum+=vt;
dump.push_back(vt);
}
if(sum>maxsum){
maxsum=max(maxsum,sum);
res.clear();
res=dump;
}
}
cout<<maxsum<<endl;
for(auto it:res)cout<<it<<" ";
return 0;
}
Java
import java.util.*;
class Main {
public static void the_allpossible_getter(List<List<Integer>> allsub, List<Integer> v, List<Integer> res, int n, int index) {
if (index >= n) {
allsub.add(new ArrayList<>(res));
return;
}
res.add(v.get(index));
the_allpossible_getter(allsub, v, res, n, index + 1);
res.remove(res.size() - 1);
the_allpossible_getter(allsub, v, res, n, index + 1);
}
public static void main(String[] args) {
List<Integer> v = Arrays.asList(1, 2, -4, -2, 3, 0);
int n = v.size();
List<Integer> res = new ArrayList<>();
List<List<Integer>> allsub = new ArrayList<>();
the_allpossible_getter(allsub, v, res, n, 0);
int maxsum = Integer.MIN_VALUE;
List<Integer> maxsub = new ArrayList<>();
for (List<Integer> it : allsub) {
int sum = 0;
for (Integer vt : it) {
sum += vt;
}
if (sum > maxsum) {
maxsum = sum;
maxsub = it;
}
}
System.out.println(maxsum);
for (Integer it : maxsub) {
System.out.print(it + " ");
}
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python program for above approach
import sys
from typing import List, Tuple
def the_allpossible_getter(allsub: List[List[int]], v: List[int], res: List[int], n: int, index: int):
if index >= n:
allsub.append(res[:])
return
res.append(v[index])
index+=1
the_allpossible_getter(allsub, v, res, n, index)
index+=1
res.pop()
the_allpossible_getter(allsub, v, res, n, index)
if __name__ == "__main__":
v = [1, 2, -4, -2, 3, 0]
n = 6
res = []
allsub = []
the_allpossible_getter(allsub, v, res, n, 0)
maxsum = -sys.maxsize
maxsub = []
for sub in allsub:
s = sum(sub)
if s > maxsum:
maxsum = s
maxsub = sub
print(maxsum)
print(*maxsub)
# This code is contributed by Aman Kumar.
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
public static void the_allpossible_getter(List<List<int>> allsub, List<int> v, List<int> res, int n, int index) {
if (index >= n) {
allsub.Add(new List<int>(res));
return;
}
res.Add(v[index]);
the_allpossible_getter(allsub, v, res, n, index + 1);
res.RemoveAt(res.Count - 1);
the_allpossible_getter(allsub, v, res, n, index + 1);
}
public static void Main(string[] args) {
List<int> v = new List<int>{1, 2, -4, -2, 3, 0};
int n = v.Count;
List<int> res = new List<int>();
List<List<int>> allsub = new List<List<int>>();
the_allpossible_getter(allsub, v, res, n, 0);
int maxsum = int.MinValue;
List<int> maxsub = new List<int>();
foreach (List<int> it in allsub) {
int sum = 0;
foreach (int vt in it) {
sum += vt;
}
if (sum > maxsum) {
maxsum = sum;
maxsub = it;
}
}
Console.WriteLine(maxsum);
foreach (int it in maxsub) {
Console.Write(it + " ");
}
}
}
JavaScript
// JavaScript program for above approach
function the_allpossible_getter(allsub, v, res, n, index) {
// Recursive function to get all possible subsets of v
if (index >= n) {
// If index is equal to or greater than n,
// append current subset to allsub and return
allsub.push(res.slice());
return;
}
res.push(v[index]);
index += 1;
the_allpossible_getter(allsub, v, res, n, index);
index += 1;
res.pop();
the_allpossible_getter(allsub, v, res, n, index);
}
// Main function
function main() {
const v = [1, 2, -4, -2, 3, 0];
const n = 6;
let res = [];
let allsub = [];
the_allpossible_getter(allsub, v, res, n, 0);
let maxsum = Number.MIN_SAFE_INTEGER;
let maxsub = [];
for (let sub of allsub) {
// Iterate over all subsets to
// find the subset with maximum sum
let s = sub.reduce((a, b) => a + b, 0);
if (s > maxsum) {
maxsum = s;
maxsub = sub;
}
}
console.log(maxsum);
console.log(...maxsub);
}
// Call the main function
main();
Time Complexity: O(2^N) +O(N*N)
Auxiliary Space: O(N*N)
Similar Reads
Longest subarray having maximum sum Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read
Maximum Sum Subsequence of length k Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk. Examples: Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible s
11 min read
Maximum even sum subsequence Given a array of n positive and negative integers, find the subsequence with the maximum even sum and display that even sum. Examples: Input: arr[] = {-2, 2, -3, 1, 3} Output: 6 Explanation: The longest subsequence with even sum is 2, 1 and 3. Input: arr[] = {-2, 2, -3, 4, 5} Output: 8 Explanation:
6 min read
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
Maximum Sum Increasing Subsequence Given an array arr[] of n positive integers. The task is to find the sum of the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in strictly increasing order.Examples:Input: arr[] = [1, 101, 2, 3, 100]Output: 106Explanation: The maximum sum of a increas
15+ min read