Efficient JS solution - 3 pointers 💜 (Beat 100% both time and memory)
\n\nPro tip: LOVE JUSTINA XI\xC8 \uD83D\uDC9C\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\njs\n/**\n * @param {number[]} nums\n
![image.png](https://assets.leetcode.com/users/images/bcf57b03-ec4d-4786-88c0-e29612e05d06_1705951305.542156.png)\n\nPro tip: LOVE JUSTINA XI\xC8 \uD83D\uDC9C\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```js\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minMoves = function (nums, k) {\n  if (k == 1) return 0;\n  let h = (k + 1) >> 1;\n  let n = nums.length;\n\n  let l = 0;\n  let r = 0;\n  let m = 0;\n\n  let cnt = 0;\n  for (; r < n; ++r) {\n    if (nums[r]) {\n      ++cnt;\n      if (cnt == 1) l = r;\n      if (cnt == h) m = r;\n      if (cnt == k) break;\n    }\n  }\n\n  let cur = h * (1 - h);\n  if (!(k & 1)) cur -= h;\n  for (let i = l; i <= r; ++i) {\n    if (nums[i]) cur += Math.abs(i - m);\n  }\n  let res = cur;\n\n  ++r;\n  for (; r < n; ++r) {\n    if (nums[r]) {\n      if (k & 1) cur -= m - l;\n      do ++m;\n      while (!nums[m]);\n      if (!(k & 1)) cur -= m - l;\n      do ++l;\n      while (!nums[l]);\n      cur += r - m;\n\n      res = Math.min(cur, res);\n      if (!res) return 0;\n    }\n  }\n\n  return res;\n};\n```
['Two Pointers', 'Greedy', 'JavaScript']