Video Explanation (step by step solution with proofs)
Explanation\n\nclick here for the video\n\n# Code\n\ntypedef long long int ll;\n\nclass Solution {\n    \n    int n;\n    vector<ll> ones;\n    vector<ll> prefi
# Explanation\n\n[click here for the video](https://youtu.be/IhaC_IM8xbU)\n\n# Code\n```\ntypedef long long int ll;\n\nclass Solution {\n    \n    int n;\n    vector<ll> ones;\n    vector<ll> prefix;\n    \n    ll Converge (int l, int r, int pos) {        \n        ll lft = (pos - l + 1)*ones[pos] - (prefix[pos] - prefix[l-1]);\n        ll rgt = (prefix[r] - prefix[pos]) - (r - pos)*ones[pos];\n                \n        return (lft + rgt);\n    }\n    \npublic:\n    long long minimumMoves(vector<int>& nums, int k, int maxChanges) {\n        n = nums.size();\n        \n        int max_consecutive = 0;\n        for (int i = 0; i < n; i ++) {\n            int cnt = 0;\n            for (int j = 0; j < 3 && i+j < n; j ++) {\n                if (nums[j+i] == 1) cnt ++;\n                else break;\n            }\n            max_consecutive = max (max_consecutive, cnt);\n        }\n                \n        if (max_consecutive+maxChanges >= k) {\n            if (k <= max_consecutive) return (k-1);\n            \n            int req_changes = k - max_consecutive;\n            int ans = req_changes*2;\n            if (max_consecutive > 0) ans += (max_consecutive - 1);\n            return ans;\n        }\n\n        \n        ones = {-1};\n        prefix = {0};\n        for (int i = 0; i < n; i ++)\n            if (nums[i] == 1) {\n                ones.push_back(i);\n                prefix.push_back(prefix.back() + i);\n            }\n        \n        int req_1 = k - maxChanges;\n        ll ans = 1e18;\n        \n        for (int l = 1, r = req_1; r < ones.size(); l ++, r ++) {\n            int best_pos = (l + r)/2;\n            ans = min (ans, Converge(l, r, best_pos));\n            // ans = min (ans, Converge(l, r, best_pos+1));\n        }\n        return ans+maxChanges*2;\n    }\n};\n```
['C++']