[Java/C++] O(n) Solution
C++ Solution:-\n\nclass Solution {\npublic:\n    int minMoves(vector<int>& nums, int k) {\n        vector<int> temp;\n        for(int i = 0; i < nums.size(); i+
**C++ Solution:-**\n```\nclass Solution {\npublic:\n    int minMoves(vector<int>& nums, int k) {\n        vector<int> temp;\n        for(int i = 0; i < nums.size(); i++) if(nums[i] == 1) temp.push_back(i);\n        for(int i = 0; i < temp.size(); i++) temp[i] -= i;\n        \n        int median = (k - 1)/2;\n        int ans = INT_MAX, l_sum = 0, r_sum = 0;\n        int l, r;\n        if(k % 2) l = r = (k/2);\n        else {\n            l = (k/2 - 1);\n            r = k/2;\n        }\n        \n        for(int i = 0; i < median; i++) l_sum += (temp[median] - temp[i]);\n        for(int i = median+1; i < k; i++) r_sum += (temp[i] - temp[median]);\n        ans = (l_sum + r_sum);\n        for(int i = k; i < temp.size(); i++){\n            l_sum -= temp[median] - temp[i - k];\n            l_sum += l*(temp[median+1] - temp[median]);\n            r_sum += temp[i] - temp[median + 1];\n            r_sum -= r*(temp[median+1]-temp[median]);\n            ans = min(ans, l_sum + r_sum);\n            median++;\n        }\n        return ans;\n    }\n};\n```\n\n**Java Solution:-**\n```\nclass Solution {\n    public int minMoves(int[] nums, int k) {\n        ArrayList<Integer> arr = new ArrayList();\n        for(int i = 0; i < nums.length; i++) if(nums[i] == 1) arr.add(i);\n        for(int i = 0; i < arr.size(); i++) arr.set(i, arr.get(i) - i);\n        \n        int median = (k-1)/2;\n        int ans = Integer.MAX_VALUE, l_sum = 0, r_sum = 0;\n        int left, right;\n        if(k % 2 == 1) left = right = k/2;\n        else {\n            left = (k/2 -1);\n            right = k/2;\n        }\n        \n        for(int i = 0; i < median; i++) l_sum += arr.get(median) - arr.get(i);\n        for(int i = median + 1; i < k; i++) r_sum += arr.get(i) - arr.get(median);\n        ans = l_sum + r_sum;\n        \n        for(int i = k; i < arr.size(); i++) {\n            l_sum -= arr.get(median) - arr.get(i - k);\n            l_sum += left * (arr.get(median + 1) - arr.get(median));\n            r_sum += arr.get(i) - arr.get(median + 1);\n            r_sum -= right * (arr.get(median + 1) - arr.get(median));\n            ans = Math.min(ans, l_sum + r_sum);\n            median++;\n        }\n        return ans;\n    }\n}\n```
[]