← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
You are given a list of positive integers weights and a positive integer target. Your task is to rescale the integers so that their sum becomes exactly target while keeping the proportions as close as possible. Formally, implement a function rescale(weights, target) that returns a list res of the same length such that:
sum(res) == target.sum(|res[i] - weights[i] * target / total|) where total = sum(weights).Use the two-step apportionment algorithm: first assign each bucket the floor of its exact share, then distribute the leftover units one-by-one to the buckets with the largest remainders. Break ties by the original index order. If total == 0 (all weights zero), distribute target evenly (as evenly as possible). If target == 0, return all zeros. You must use only integer arithmetic to avoid floating-point precision issues.