Simple C++ code using 3 pointers, O(N) time O(1) space
\nint minMoves(vector<int>& nums, int k) {\n\n\tint f = 0, m = 0, l = 0;\n\tint cnt = 0;\n\n\tfor (int i = 0; cnt < k; ++i) {\n\t\tif (nums[i] == 1) {\n\t\t\t++
```\nint minMoves(vector<int>& nums, int k) {\n\n\tint f = 0, m = 0, l = 0;\n\tint cnt = 0;\n\n\tfor (int i = 0; cnt < k; ++i) {\n\t\tif (nums[i] == 1) {\n\t\t\t++cnt;\n\t\t\tif (cnt == 1) f = i;\n\t\t\tif (cnt == (k + 1) / 2) m = i;\n\t\t\tif (cnt == k) l = i;\n\t\t}\n\t}\n\n\tint dist = 0;\n\tcnt = 1;\n\n\tfor (int i = f; i <= l; ++i) {\n\t\tif (nums[i] == 0) continue;\n\t\tdist += abs(i - m);\n\t\tif (i == m) cnt = 0;\n\t\tdist -= cnt;\n\t\t++cnt;\n\t}\n\n\tint res = dist;\n\tint prev = m;\n\n\tfor (++m; m < nums.size(); ++m) {\n\n\t\tif (nums[m] == 0) continue;\n\n\t\tdist += (k % 2) * (m - prev);\n\t\tdist -= (m - f);\n\n\t\twhile (nums[++f] == 0);\n\t\tfor (++l; l < nums.size() && nums[l] == 0; ++l);\n\t\tif (l >= nums.size()) break;\n\n\t\tdist += (l - m);\n\n\t\tres = min(res, dist);\n\t\tprev = m;\n\t}\n\n\treturn res;\n}\n```
[]