Cap the highest values in a list so that the sum equals a given number

Python 3, 70 77 56 bytes

-21 bytes thanks to Jonathan Allan!

def f(l,n):
 while n/all(l)<sum(l):l[l.index(max(l))]-=1

Try it online!


PHP>=7.1, 94 bytes

<?for([$a,$s]=$_GET;array_sum($a)>$s;)$a[array_flip($a)[max($a)]]--;print_r(min($a)?$a:0);

replace array_flip($a)[max($a)] with array_search(max($a),$a) to cap the last/first item with the maximum value

PHP Sandbox Online


Mathematica, 79 bytes

(u:=Plus@@a;For[a=#2,u>#,a[[#&@@a~Position~Max@a]]--];Min@a>0&&u==#||Quit[];a)&

Takes sum and List of integers