![]() |
VOOZH | about |
Given an array arr[] of length n, where arr[i] is the number of soldiers in the i-th troop, and an integer k. A troop is called lucky if its soldier count is a multiple of k. Find the minimum total number of soldiers to add across all troops so that at least βn / 2β troops become lucky. You may add any number of soldiers to any troop.
Examples:
Input: arr[] = [3, 5, 6, 7, 9, 10], k = 4
Output: 4
Explanation: We need at least 3 lucky troops since β 6 / 2 β = 3.
Currently, no troop is divisible by 4.
Add 1 soldier for troop 3 β 4,
Add 2 for troop 6 β 8,
Add 1 for troop 7 β 8.
New array: [4, 5, 8, 8, 9, 10] with 3 lucky troops (4, 8, 8).
Total soldiers added = 4.Input: arr[] = [5, 6, 3, 2, 1], k = 2
Output: 1
Explanation: Add 1 soldier to the troop with 1 soldier β arr = [5, 6, 3, 2, 2].
Now 3 troops (6, 2, and 2) are divisible by 2. Since β 5/2 β = 3, the requirement is met.
Table of Content
The main idea is to try all possible subset of troops that could be made lucky and calculate the minimum total number of soldiers needed.
For each selected troop, if its current count arr[i] is not divisible by k, we compute the number of soldiers to add as k - (arr[i] % k), this is the smallest amount needed to reach the next multiple of k.
We sum up these additions for each valid combination and pick the one with the least total soldiers added.
The idea is to calculate how many soldiers need to be added to each troop to make it lucky, means divisible by k. If a troop is already lucky, the cost is zero. Otherwise, the cost to make it lucky is calculated as k - (arr[i] % k). We collect these costs for all troops and sort them in increasing order. Since we need at least half of the troops to be lucky, we select the smallest ceil(n / 2) costs and add them.
We can further optimize by first counting how many troops are already lucky. If thatβs enough, we return zero. Otherwise, we compute costs only for the unlucky troops and pick the smallest ones needed to reach the target, avoiding full sorting.
Time Complexity: O(n + m * log(m)), where m is the number of unlucky troops (at most n).
Auxiliary Space: O(m)