Maximum size subset with given sum using Backtracking | Initialise maximum possible length of subsequence ; Store elements to compare max_length with its size and change the value of max_length accordingly ; Store the elements of the longest subsequence ; Function to find the length of longest subsequence ; Update max_length ; Store the subsequence elements ; Recursively proceed with obtained sum ; poping elements from back of vector store ; if sum > 0 then we don 't  required thatsubsequence  so return and continue  with earlier elements ; Sort the given array ; Traverse the array ; If max_length is already greater than or equal than remaining length ; Driver code
let max_length = 0 ; let store = [ ] ; let ans = [ ] ; function find_max_length ( arr , index , sum , k ) { sum = sum + arr [ index ] ; store . push ( arr [ index ] ) ; if ( sum == k ) { if ( max_length < store . length ) { max_length = store . length ; ans = store ; } } for ( let i = index + 1 ; i < arr . length ; i ++ ) { if ( sum + arr [ i ] <= k ) { find_max_length ( arr , i , sum , k ) ; store . pop ( ) ; } else return ; } return ; } function longestSubsequence ( arr , n , k ) { arr . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( max_length >= n - i ) break ; store = [ ] ; find_max_length ( arr , i , 0 , k ) ; } return max_length ; } let arr = [ - 3 , 0 , 1 , 1 , 2 ] ; let n = arr . length ; let k = 1 ; document . write ( longestSubsequence ( arr , n , k ) ) ;