Longest sub | Java 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
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 ) ) ; } }