Maximum profit such that total stolen value is less than K to get bonus | Function to find the maximum profit from the given values ; Iterating over every possible permutation ; Driver code ; Function call
function maxProfit ( value , N , K ) { value . sort ( ) ; let maxval = value [ N - 1 ] ; let maxProfit = 0 ; let curr_val ; do { curr_val = 0 ; for ( let i = 0 ; i < N ; i ++ ) { curr_val += value [ i ] ; if ( curr_val <= K ) { maxProfit = Math . max ( curr_val + maxval * ( i + 1 ) , maxProfit ) ; } } } while ( next_permutation ( value ) ) ; return maxProfit ; } function next_permutation ( p ) { for ( let a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( let b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { let t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } let N = 4 , K = 6 ; let values = [ 5 , 2 , 7 , 3 ] ; document . write ( maxProfit ( values , N , K ) ) ;