Minimum boxes required to carry all gifts | Java implementation of above approach ; 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 program
import java . util . * ; class solution { static int numBoxes ( int A [ ] , int n , int K ) { Arrays . sort ( A ) ; int i = 0 , j = n - 1 ; int ans = 0 ; while ( i <= j ) { ans ++ ; if ( A [ i ] + A [ j ] <= K ) i ++ ; j -- ; } return ans ; } public static void main ( String args [ ] ) { int A [ ] = { 3 , 2 , 2 , 1 } , K = 3 ; int n = A . length ; System . out . println ( numBoxes ( A , n , K ) ) ; } }