Problem Description
Given an even-length integer array nums and an integer limit, you can change any element in nums to any value between 1 and limit in one move. The array is called complementary if for every index i, the sum nums[i] + nums[n-1-i] is the same. The goal is to compute the minimum number of moves required to convert nums into a complementary array.
Key Insights
- Every pair (nums[i], nums[n-1-i]) contributes to a target sum.
- Without any changes, each pair would require 2 moves.
- However, if one of the elements in the pair can be adjusted smartly, some sums may be achievable with only 1 move or even 0 moves.
- For each pair, there is a range of sums that can be achieved with 1 move.
- A difference array (or prefix sum technique) can efficiently tally the change in cost for all potential sums.
- After processing all pairs, iterating over all possible sums gives the minimal total moves required.
Space and Time Complexity
Time Complexity: O(n + limit) – each pair is processed in constant time and then we iterate over 2limit possible sums.
Space Complexity: O(limit) – using an auxiliary array of size proportional to 2limit to store differences.
Solution
We start by noting that without any modifications, each pair would need 2 moves. For each symmetric pair (a, b), we can achieve the following:
- With 0 moves if the pair already sums to a desired value.
- With 1 move if we can change one of them such that the new sum lies in the interval [min(a, b) + 1, max(a, b) + limit].
- With 2 moves if neither of the above conditions is possible.
We use a difference array (or prefix sum array) to track the change in the number of moves required for each possible target sum. For each pair:
- We add an initial cost of 2 moves.
- In the interval [min(a, b) + 1, max(a, b) + limit], we can reduce the cost by 1 (making it 1 move in total).
- At exactly the sum a + b, we can reduce the cost by another move (making it 0 moves).
After processing all pairs, we compute a prefix sum over the difference array to derive the total moves required for each possible target sum. Finally, we take the minimum value as our answer.