Maximum sum subarray having sum less than or equal to given sum using Set | Function to maximum required sum < K ; Hash to lookup for value ( cum_sum - K ) ; Getting cummulative sum from [ 0 to i ] ; Lookup for upperbound of ( cSum - K ) in hash ; Check if upper_bound of ( cSum - K ) exists then update max sum ; Insert cummulative value in hash ; Return maximum sum lesser than K ; Initialise the array ; Initialise the value of K ; Size of array
function maxSubarraySum ( arr , N , K ) { let cum_set = new Set ( ) ; cum_set . add ( 0 ) ; let max_sum = Number . MIN_SAFE_INTEGER ; let cSum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { cSum += arr [ i ] ; let al = [ ] ; let end = 0 ; for ( let it of cum_set ) { end = it ; al . push ( it ) ; } al . sort ( ( a , b ) => a - b ) ; let sit = lower_bound ( al , cSum - K ) ; if ( sit != end ) max_sum = Math . max ( max_sum , cSum - sit ) ; cum_set . add ( cSum ) ; } return max_sum ; } let lower_bound = ( al , x ) => al . filter ( ( item ) => item > x ) [ 0 ] let arr = [ 5 , - 2 , 6 , 3 , - 5 ] ; let K = 15 ; let N = arr . length ; document . write ( maxSubarraySum ( arr , N , K ) ) ;