Order of indices which is lexicographically smallest and sum of elements is <= X | Function to return the chosen indices ; Maximum indices chosen ; Try to replace the first element in ans by i , making the order lexicographically smaller ; If no further replacement possible return ; If found an index smaller than ind and sum not exceeding X then remove index of smallest value from ans and then add index i to ans ; Driver code ; Print the chosen indices
function solve ( X , A ) { let min = Number . MAX_VALUE ; let ind = - 1 ; for ( let i = 0 ; i < A . length ; i ++ ) { if ( A [ i ] < min ) { min = A [ i ] ; ind = i ; } } let maxIndChosen = Math . floor ( X / min ) ; let ans = [ ] ; if ( maxIndChosen == 0 ) { return ans ; } for ( let i = 0 ; i < maxIndChosen ; i ++ ) { ans . push ( ind ) ; } let temp = maxIndChosen ; let sum = maxIndChosen * A [ ind ] ; for ( let i = 0 ; i < ind ; i ++ ) { if ( sum - X == 0 temp == 0 ) break ; while ( ( sum - A [ ind ] + A [ i ] ) <= X && temp != 0 ) { ans . shift ( ) ; ans . push ( i ) ; temp -- ; sum += ( A [ i ] - A [ ind ] ) ; } } ans . sort ( function ( a , b ) { return a - b ; } ) ; return ans ; } let A = [ 5 , 6 , 4 , 8 ] ; let X = 18 ; let ans = solve ( X , A ) ; for ( let i = 0 ; i < ans . length ; i ++ ) document . write ( ans [ i ] + " " ) ;