Longest sub | C ++ implementation of the approach ; Function to return the length of the largest subsequence with non - negative sum ; To store the current sum ; Sort the input array in non - increasing order ; Traverse through the array ; Add the current element to the sum ; Condition when c_sum falls below zero ; Complete array has a non - negative sum ; Driver code
#include <bits/stdc++.h> NEW_LINE 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 ; }