function fn(input, total) {
const output = [];
const order = input.map((_, index) => index);
const sortedOrder = order.sort((a, b) => input[b] - input[a]);
const mustCheckIndexes = [];
for (let i = 0; i < sortedOrder.length; i++) {
const sortedIndex = sortedOrder[i];
if (i === 0) {
mustCheckIndexes.push(sortedIndex);
} else if (input[sortedIndex] === input[sortedOrder[i - 1]]) mustCheckIndexes.push(sortedIndex);
else break;
}
for (let i = 0; total; i = ++i % input.length) {
let breakCycle = false;
for (const mustCheckIndex of mustCheckIndexes) {
if (output[mustCheckIndex] === input[mustCheckIndex]) breakCycle = true;
else breakCycle = false;
}
if (breakCycle) break;
const currIndex = sortedOrder[i];
output[currIndex] = output[currIndex] || 0;
if (output[currIndex] + 1 > input[currIndex]) {
continue;
}
output[currIndex]++;
total--
}
return output
};