Longest sub-sequence with non-negative sum
Given an array arr[] of length N, the task is to find the length of the largest sub-sequence with non-negative sum.
Examples:
Input: arr[] = {1, 2, -3}
Output: 3
The complete array has a non-negative sum.
Input: arr[] = {1, 2, -4}
Output: 2
{1, 2} is the required subsequence.
Approach: The idea is that all the non-negative numbers must be included in the sub-sequence because such numbers will only increase the value of the total sum.
Now, it’s not hard to see among negative numbers, the larger ones must be chosen first. So, keep adding the negative numbers in non-increasing order of their values as long as they don’t decrease the value of the total sum below 0. This can be done after sorting the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxLen( int * arr, int n)
{
int c_sum = 0;
sort(arr, arr + n, greater< int >());
for ( int i = 0; i < n; i++) {
c_sum += arr[i];
if (c_sum < 0)
return i;
}
return n;
}
int main()
{
int arr[] = { 3, 5, -6 };
int n = sizeof (arr) / sizeof ( int );
cout << maxLen(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int maxLen( int [] arr, int n)
{
int c_sum = 0 ;
Arrays.sort(arr);
for ( int i = n- 1 ; i >= 0 ; i--)
{
c_sum += arr[i];
if (c_sum < 0 )
return i;
}
return n;
}
public static void main(String []args)
{
int arr[] = { 3 , 5 , - 6 };
int n = arr.length;
System.out.println(maxLen(arr, n));
}
}
|
Python3
def maxLen(arr, n) :
c_sum = 0 ;
arr.sort(reverse = True );
for i in range (n) :
c_sum + = arr[i];
if (c_sum < 0 ) :
return i;
return n;
if __name__ = = "__main__" :
arr = [ 3 , 5 , - 6 ];
n = len (arr);
print (maxLen(arr, n));
|
C#
using System;
class GFG
{
static int maxLen( int [] arr, int n)
{
int c_sum = 0;
Array.Sort(arr);
for ( int i = n - 1; i >= 0; i--)
{
c_sum += arr[i];
if (c_sum < 0)
return i;
}
return n;
}
public static void Main(String []args)
{
int []arr = { 3, 5, -6 };
int n = arr.Length;
Console.WriteLine(maxLen(arr, n));
}
}
|
Javascript
<script>
function maxLen(arr, n)
{
var c_sum = 0;
arr.sort((a,b)=> b-a)
for ( var i = 0; i < n; i++) {
c_sum += arr[i];
if (c_sum < 0)
return i;
}
return n;
}
var arr = [3, 5, -6];
var n = arr.length;
document.write( maxLen(arr, n));
</script>
|
Time Complexity: O(n*log(n))
Auxiliary Space: O(1)
Last Updated :
24 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...