1674. Minimum Moves to Make Array Complementary

https://leetcode.com/problems/minimum-moves-to-make-array-complementary/

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.length

  • 2 <= n <= 105

  • 1 <= nums[i] <= limit <= 105

  • n is even.

数组nums如果对所有元素都满足nums[i] + nums[n - 1 - i]则称作互补,现能让每个数都变成[1, limit]之中任意数,问让nums互补的最少变动次数。让T为互补时的可能值,a和b为nums[i]和nums[n - 1 - i],分5种情况:

  1. 2 <= T < min(a, b) + 1, 需要a和b都变小,两次变动;

  2. min(a, b) + 1 <= T < a + b 需要max(a, b)变小,一次变动

  3. a + b = T 无需变动

  4. a + b < T <= max(a, b) + limit 需要min(a, b)变大,一次变动

  5. max(a, b) + limit < T <= 2 * limit 需要a和b都变大,两次变大

根据以上观察遍历所有ab对,并更新delta,delta为T从i-1到i时变动数目的变化量。再用扫描线遍历T的所有可能[2, 2 * limit],cur_i += delta[i]为T = i时所需变动数目。min(cur[i])为所求。

参考了

class Solution:
    def minMoves(self, nums: List[int], limit: int) -> int:
        N, delta = len(nums), collections.Counter()
        for i in range(N // 2):
            a, b = nums[i], nums[N - 1 - i]
            # 2 <= T < min(A, B) + 1, we need 2 operations to make both A, B smaller
            delta[2] += 2
            # min(A, B) + 1 <= T < A + B, we need 1 operation to make the larger one out of A and B smaller
            delta[min(a, b) + 1] -= 1
            # T = A + B, we need 0 operation
            delta[a + b] -= 1
            # A + B < T < max(A, B) + limit, we need 1 operation to make the smaller one out of A and B larger
            delta[a + b + 1] += 1
            # max(A, B) + limit < T <= 2 * limit, we need 2 operation to make both A, B larger
            delta[max(a, b) + limit + 1] += 1
            cur, res = 0, math.inf
        for i in range(2, 2 * limit + 1):
            cur += delta[i]
            res = min(res, cur)
        return res
        

Last updated