|
| 1 | +/** |
| 2 | + * 1674. Minimum Moves to Make Array Complementary |
| 3 | + * https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer array nums of even length n and an integer limit. In one move, you |
| 7 | + * can replace any integer from nums with another integer between 1 and limit, inclusive. |
| 8 | + * |
| 9 | + * The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] |
| 10 | + * equals the same number. For example, the array [1,2,3,4] is complementary because for all |
| 11 | + * indices i, nums[i] + nums[n - 1 - i] = 5. |
| 12 | + * |
| 13 | + * Return the minimum number of moves required to make nums complementary. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[]} nums |
| 18 | + * @param {number} limit |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var minMoves = function(nums, limit) { |
| 22 | + const n = nums.length; |
| 23 | + const delta = new Array(2 * limit + 2).fill(0); |
| 24 | + let result = n; |
| 25 | + |
| 26 | + for (let i = 0; i < n / 2; i++) { |
| 27 | + const left = nums[i]; |
| 28 | + const right = nums[n - 1 - i]; |
| 29 | + const minSum = Math.min(left, right) + 1; |
| 30 | + const maxSum = Math.max(left, right) + limit; |
| 31 | + delta[2] += 2; |
| 32 | + delta[minSum] -= 1; |
| 33 | + delta[left + right] -= 1; |
| 34 | + delta[left + right + 1] += 1; |
| 35 | + delta[maxSum + 1] += 1; |
| 36 | + } |
| 37 | + |
| 38 | + let moves = 0; |
| 39 | + for (let i = 2; i <= 2 * limit; i++) { |
| 40 | + moves += delta[i]; |
| 41 | + result = Math.min(result, moves); |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | +}; |
0 commit comments