Minimum boxes required to carry all gifts | Function to return number of boxes ; Sort the boxes in ascending order ; Try to fit smallest box with current heaviest box ( from right side ) ; Driver code
function numBoxes ( A , n , K ) { A . sort ( function ( a , b ) { return a - b } ) ; let i = 0 , j = ( n - 1 ) ; let ans = 0 ; while ( i <= j ) { ans ++ ; if ( A [ i ] + A [ j ] <= K ) i ++ ; j -- ; } return ans ; } let A = [ 3 , 2 , 2 , 1 ] ; let K = 3 ; let n = A . length ; document . write ( numBoxes ( A , n , K ) ) ;