Skip to content

Latest commit

 

History

History
42 lines (28 loc) · 961 Bytes

1674. 使数组互补的最少操作次数.md

File metadata and controls

42 lines (28 loc) · 961 Bytes
  • 差分数组
function minMoves(nums: number[], limit: number): number {

    const diff: number[] = new Array(2 * limit + 2).fill(0);

    let left: number = 0,
        right: number = nums.length - 1,
        result: number = 2 * nums.length;

    while (left < right) {

        diff[2] += 2;
        diff[2 * limit + 1] -= 2;

        const min: number = Math.min(nums[left], nums[right]),
            max: number = Math.max(nums[left], nums[right]),
            sum: number = nums[left] + nums[right];

        diff[min + 1] -= 1;
        diff[max + limit + 1] += 1;

        diff[sum] -= 1;
        diff[sum + 1] += 1;

        ++left;
        --right;
    }

    for (let i = 2; i <= 2 * limit; ++i) {
        diff[i] += diff[i - 1];
        result = Math.min(result, diff[i]);
    }

    return result;

};