VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tywin-s-war-strategy/

⇱ Tywin's War Strategy - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tywin's War Strategy

Last Updated : 18 Jul, 2025

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.

[Naive Approach] Generating All Sub Set - O(n * 2n) Time and O(1) Space

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.

[Expected Approach - 1] Using Sorting - O(n log(n)) Time and O(n) Space

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.

[Expected Approach 2] Using Min Heap

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)

Comment
Article Tags:
Article Tags: