Iterating over every possible permutation
while True : NEW_LINE INDENT curr_val = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_val += value [ i ] NEW_LINE if ( curr_val <= K ) : NEW_LINE INDENT maxProfit = max ( curr_val + maxval * ( i + 1 ) , maxProfit ) NEW_LINE DEDENT DEDENT if not next_permutation ( value ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return maxProfit NEW_LINE def next_permutation ( p ) : NEW_LINE for a in range ( len ( p ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT if p [ a ] < p [ a + 1 ] : NEW_LINE INDENT b = len ( p ) - 1 NEW_LINE while True : NEW_LINE INDENT if p [ b ] > p [ a ] : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b = len ( p ) - 1 NEW_LINE while a < b : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT b -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE