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.
Solution: Sweep Line / Prefix Sum
Let a = min(nums[i], nums[n-i-1]), b = max(nums[i], nums[n-i-1])
The key to this problem is how many moves do we need to make a + b == T.
if 2 <= T < a + 1, two moves, lower both a and b.
if a +1 <= T < a + b, one move, lower b
if a + b == T, zero move
if a + b + 1 <= T < b + limit + 1, one move, increase a
if b + limit + 1 <= T <= 2*limit, two moves, increase both a and b.
Time complexity: O(n + limit) or O(nlogn) if limit >>n
Space complexity: O(limit) or O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua class Solution { public: int minMoves(vector<int>& nums, int limit) { const int n = nums.size(); vector<int> delta(limit * 2 + 2); for (int i = 0; i < n / 2; ++i) { const int a = min(nums[i], nums[n - i - 1]); const int b = max(nums[i], nums[n - i - 1]); delta[2] += 2; // dec a, dec b --delta[a + 1]; // dec a --delta[a + b]; // no op ++delta[a + b + 1]; // inc a ++delta[b + limit + 1]; // inc a, inc b } int ans = n; for (int t = 2, cur = 0; t <= limit * 2; ++t) { cur += delta[t]; ans = min(ans, cur); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment