O(n) Time O(1) Space Solution With Three Pointers
We want the medium of k size of 1\'s sequence as the center meet point to move all 1\'s together.\nUse three pointer: start, mid and end to mark the current win
We want the medium of k size of 1\'s sequence as the center meet point to move all 1\'s together.\nUse three pointer: `start`, `mid` and `end` to mark the current window\'s start, middle and end point.\nCalculate the result for the first window. Then each time when we find a new 1 to add into the window, update the result by below 3 steps:\n1. Remove the left most 1 and update the result by `cur -= mid-start-half`, We can easily prove that `mid-start-half` is the number of 0s in the 1st half. And move pointer `start` to the next position of 1.\n2. Move pointer `mid` to the next position of 1. If k is even, we need to add the number of 0s between previous `mid` and next `mid` because the number of 1s in the 1st half is always greater than the 2nd half by 1. \n3. Add the new right most 1 into window and update the result by` cur += end-mid-(half-1+k%2)`.\n\n```\nclass Solution {\n    public int minMoves(int[] nums, int k) {\n        if(k<=1)return 0;\n        int res=0, start=0, mid=0, end, cur=0, half=k/2; \n        for(end=0;end<nums.length && cur<k;++end){\n            if(nums[end]==0){\n                if(cur<=half)res+=cur;\n            }else{\n                ++cur;\n                if(cur==half+1)mid = end;\n                else if(cur>half+1)res += end-mid-(cur-(half+1));\n                else if(cur==1)start = end;\n            }\n        }\n        cur = res;\n        while(end < nums.length){\n            while(end<nums.length && nums[end]==0)end++;\n            if(end < nums.length){\n                cur -= mid-start-half; //remove the left most 1.\n                while(nums[++start]==0);\n                while(nums[++mid]==0){\n                    if(k%2==0)++cur;\n                }\n                cur += end-mid-(half-1+k%2); //add the new right most 1.\n                res = Math.min(res, cur);\n                ++end;\n            }\n        }\n        return res;\n    }\n}\n```
[]