Created
May 13, 2026 19:09
-
-
Save tatsuyax25/feee4efcdc0a6754b712169e30acd9e3 to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @param {number} limit | |
| * @return {number} | |
| */ | |
| var minMoves = function(nums, limit) { | |
| const n = nums.length; | |
| const diff = new Array(2 * limit + 2).fill(0); | |
| for (let i = 0; i < n / 2; i++) { | |
| const a = nums[i]; | |
| const b = nums[n - 1 - i]; | |
| const mn = Math.min(a, b); | |
| const mx = Math.max(a, b); | |
| const s = a + b; | |
| // Base: everything costs 2 moves | |
| diff[2] += 2; | |
| diff[2 * limit + 1] -= 2; | |
| // One-move range | |
| diff[mn + 1] -= 1; | |
| diff[mx + limit + 1] += 1; | |
| // Zero-move point | |
| diff[s] -= 1; | |
| diff[s + 1] += 1; | |
| } | |
| let ans = Infinity; | |
| let curr = 0; | |
| for (let x = 2; x <= 2 * limit; x++) { | |
| curr += diff[x]; | |
| ans = Math.min(ans, curr); | |
| } | |
| return ans; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment