Minimum Moves to Make Array Complementary Problem
Description
LeetCode Problem 1674.
You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.
The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.
Return the minimum number of moves required to make nums complementary.
Example 1:
Input: nums = [1,2,4,3], limit = 4
Output: 1
Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).
nums[0] + nums[3] = 1 + 3 = 4.
nums[1] + nums[2] = 2 + 2 = 4.
nums[2] + nums[1] = 2 + 2 = 4.
nums[3] + nums[0] = 3 + 1 = 4.
Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.
Example 2:
Input: nums = [1,2,2,1], limit = 2
Output: 2
Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.
Example 3:
Input: nums = [1,2,1,2], limit = 2
Output: 0
Explanation: nums is already complementary.
Constraints:
n == nums.length2 <= n <= 10^51 <= nums[i] <= limit <= 10^5nis even.
Solution
Approach: Difference Array Over the Target Sum
Every pair nums[i], nums[n - 1 - i] must end up with the same sum s, and s is somewhere in [2, 2 * limit]. Fix one pair and let x be its smaller and y its larger value. The number of moves this pair needs depends on s:
s = x + y: 0 moves.x + 1 <= s <= y + limit(but notx + y): 1 move, change one of the two numbers.2 <= s <= xory + limit + 1 <= s <= 2 * limit: 2 moves, both numbers must change.
So each pair adds a constant to a few ranges of s. Instead of updating every s, record the changes in a difference array d: add 2 from s = 2, drop to 1 at x + 1, drop to 0 at x + y, back to 1 at x + y + 1, and back to 2 at y + limit + 1.
After processing all pairs, the prefix sums of d give the total moves for each s, and the answer is the smallest of them.
Complexity: O(n + limit) time and O(limit) extra space.
from itertools import accumulate
class Solution:
def minMoves(self, nums: List[int], limit: int) -> int:
d = [0] * (2 * limit + 2)
n = len(nums)
for i in range(n // 2):
x, y = nums[i], nums[-i - 1]
if x > y:
x, y = y, x
d[2] += 2
d[x + 1] -= 2
d[x + 1] += 1
d[x + y] -= 1
d[x + y + 1] += 1
d[y + limit + 1] -= 1
d[y + limit + 1] += 2
return min(accumulate(d[2:]))