1703. Minimum Adjacent Swaps for K Consecutive Ones.cpp
Code\n\nclass Solution {\npublic:\n    int minMoves(vector<int>& nums, int k) {\n        vector<int> ones;\n        for(int i=0;i<nums.size();i++)\n        {\n 
**Code**\n```\nclass Solution {\npublic:\n    int minMoves(vector<int>& nums, int k) {\n        vector<int> ones;\n        for(int i=0;i<nums.size();i++)\n        {\n            if(nums[i] == 1)\n                ones.push_back(i);\n        }        \n         int n=ones.size();\n          vector<long long int> preSum(n, 0);\n         preSum[0] = ones[0];\n        for(int i=1;i<n;i++)\n            preSum[i] = preSum[i-1] + ones[i];\n        int i=0,j=0;\n       long long int ans  = LLONG_MAX;\n        while(j < n){\n            if(j-i+1 == k){\n                int mid = (j + i)/2;\n                long long int right = preSum[j] - preSum[mid];\n                long long int left = (mid-1 < 0 ? 0 : preSum[mid - 1]) - (i-1 < 0 ? 0 : preSum[i-1]);\n                int radius = (k-1)/2;\n                long long int p = (long long int)radius*(radius + 1);\n                long long int sum = right - left - p;\n                if(k % 2 == 0){\n                    sum -= (radius + 1);\n                    sum -= ones[mid];\n                }\n                ans = min(ans, sum);\n                i++;\n            }\n            j++;\n        }\n        return ans;\n    }\n};\n```
['C']