python 3 | O(n) time | O(1) space
\nclass Solution:\n    def minMoves(self, nums: List[int], k: int) -> int:\n        if k == 1:\n            return 0\n        ones = 0\n        half = (k + 1) >
```\nclass Solution:\n    def minMoves(self, nums: List[int], k: int) -> int:\n        if k == 1:\n            return 0\n        ones = 0\n        half = (k + 1) >> 1\n        leftSum = rightSum = 0\n        for i, num in enumerate(nums):\n            if not num:\n                continue\n            ones += 1\n            if ones < half:\n                leftSum += i\n                if ones == 1:\n                    left = i\n            elif ones == half:\n                mid = i\n            else:\n                rightSum += i\n                if ones == k:\n                    right = i\n                    break\n        if k == 2:\n            left = mid\n        if k & 1:\n            leftHalf = rightHalf = half - 1\n        else:\n            leftHalf, rightHalf = half - 1, half\n        leftOffset = (leftHalf*leftHalf - leftHalf) >> 1\n        rightOffset = (rightHalf*rightHalf - rightHalf) >> 1\n        cur = res = (\n            leftHalf * (mid - 1) - leftSum - leftOffset +\n            rightSum - rightHalf * (mid + 1) - rightOffset\n        )\n        n = len(nums)\n        while True:\n            right += 1\n            while right < n and not nums[right]:\n                right += 1\n            if right == n:\n                break\n            rightSum += right\n            leftSum -= left\n            left += 1\n            while not nums[left]:\n                left += 1\n            leftSum += mid\n            mid += 1\n            while not nums[mid]:\n                mid += 1\n            rightSum -= mid\n            cur = (\n                leftHalf * (mid - 1) - leftSum - leftOffset +\n                rightSum - rightHalf * (mid + 1) - rightOffset\n            )\n            res = min(res, cur)\n        return res\n            \n        \n        \n        \n\n        \n\n```
['Sliding Window', 'Python', 'Python3']