Minimum Moves to Make Array Complementary
Real-world version: Trim the Ballast TanksThe statement here is our own: the same inputs, outputs and technique.
A survey ship carries an even number of ballast tanks in one line from bow to stern. Write n for the number of tanks. Tank i is mirrored by tank n - 1 - i on the far side of midships. You are given levels, where levels[i] is how many units tank i holds right now, and an integer capacity giving the largest load any tank may hold.
A refill takes one tank and resets it to any load from 1 to capacity inclusive. Each refill counts as one, you may refill the same tank more than once, and a refill is free to leave a tank at the load it already had.
The ship is trimmed when every mirrored pair carries the same combined load, that is, levels[i] + levels[n - 1 - i] is one and the same value for every i.
Return the fewest refills that leave the ship trimmed.
Examples
Example 1
- Input
- levels = [2, 7, 6, 3, 5, 2], capacity = 9
- Output
- 2
Resetting the fifth tank to 2 and the sixth tank to 7 gives loads [2, 7, 6, 3, 2, 7]. The mirrored pairs are 2 + 7, 7 + 2 and 6 + 3, all totalling 9, which takes 2 refills.
Example 2
- Input
- levels = [2, 5, 3, 6], capacity = 7
- Output
- 0
The mirrored pairs are 2 + 6 and 5 + 3, both totalling 8, so the ship is already trimmed.
Example 3
- Input
- levels = [2, 4, 4, 2], capacity = 4
- Output
- 2
Resetting the third tank to 2 and the fourth tank to 4 gives loads [2, 4, 2, 4], whose mirrored pairs are 2 + 4 and 4 + 2, both totalling 6, which takes 2 refills.
Constraints
- n == levels.length
- 2 <= n <= 10^5
- 1 <= levels[i] <= capacity <= 10^5
- n is even
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def min_refills(levels: list[int], capacity: int) -> int:public int minRefills(int[] levels, int capacity)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Check if All the Integers in a Range Are CoveredReal-world version: Patrol Coverage AuditEasy
- Subarray Sum Equals KReal-world version: Trail Elevation StretchesMedium
- Contiguous ArrayReal-world version: Balanced Shift StretchMedium
- Count Number of Nice SubarraysReal-world version: Runs With K Odd ReadingsMedium