sliding window and prefix sum
// Based on most voted solution https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/987607/O(n)-explanation-with-picture\n\nclas
// Based on most voted solution https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/987607/O(n)-explanation-with-picture\n```\nclass Solution {\n    public int minMoves(int[] nums, int k) {\n        \n        List<Integer> onesIndex = new ArrayList<>();\n        \n        for(int i=0;i<nums.length ;i++)\n            if(nums[i] ==1)\n                onesIndex.add(i);\n        \n        int[] prefix_sum = new int[onesIndex.size()];\n        \n        prefix_sum[0] = onesIndex.get(0);\n        \n        for(int i=1;i<prefix_sum.length;i++)\n            prefix_sum[i] = prefix_sum[i-1]+onesIndex.get(i);\n        \n        int ans = Integer.MAX_VALUE;\n        \n        int left =0,right=k-1;\n        \n        while(right < onesIndex.size()){          \n            \n            int mid = left + (k + 1) / 2 - 1;            \n            int rad = mid - left;\n        \n             int rightSUm = prefix_sum[right] - prefix_sum[mid];\n            int leftSum = (mid == 0 ? 0 : prefix_sum[mid - 1]) - (left == 0 ? 0 : prefix_sum[left - 1]);\n            int cost = rightSUm -leftSum - (k%2 ==0 ? onesIndex.get(mid) : 0);\n            int save = rad * (rad + 1) + ( k%2 ==0 ? (rad + 1) : 0);\n            ans = Math.min(ans, cost -save);  \n\n            left++;\n            right++;\n        }\n\n        return ans;\n    }\n}\n```
[]