C++ O(N) solution with scope for further optimization
\nclass Solution {\npublic:\n  long long minimumMoves(vector<int>& nums, int k, int maxChanges) {\n    int n = nums.size();\n    vector<int> oneIdcs;\n    oneId
```\nclass Solution {\npublic:\n  long long minimumMoves(vector<int>& nums, int k, int maxChanges) {\n    int n = nums.size();\n    vector<int> oneIdcs;\n    oneIdcs.reserve(n);\n    for (int i = 0; i < n; ++i) {\n      if (nums[i] == 1) oneIdcs.push_back(i);\n    }\n    if (oneIdcs.empty()) return k * 2;\n    long long minMoves = -1;\n    int m = oneIdcs.size();\n    int leftMost = 0, rightMost = 0;\n    long long leftSum = 0, rightSum = 0;\n    long long diff = 0;\n    for (int i = 0; i < m; ++i) {\n      leftSum += ((i - leftMost) * diff);\n      rightSum -= (((rightMost - i) + 1) * diff);\n      long long changes = 0;\n      while ((i - leftMost) + (rightMost - i) + 1 > k) {\n        leftSum -= (oneIdcs[i] - oneIdcs[leftMost]);\n        leftMost++;\n      }\n      int tot = (i - leftMost) + (rightMost - i) + 1;\n      while (tot < k) {\n        if (rightMost + 1 < m) {\n          if (oneIdcs[rightMost + 1] - oneIdcs[i] < 2) {\n            rightSum += (oneIdcs[rightMost + 1] - oneIdcs[i]);\n            rightMost++;\n            tot++;\n          } else if (changes < maxChanges) {\n            changes++;\n            tot++;\n          } else {\n            rightSum += (oneIdcs[rightMost + 1] - oneIdcs[i]);\n            rightMost++;\n            tot++;\n          }\n        } else {\n          changes += (k - tot);\n          tot = k;\n        }\n      }\n      while (tot == k && (i - leftMost) && changes < maxChanges) {\n        if (oneIdcs[i] - oneIdcs[leftMost] > 2) {\n          leftSum -= (oneIdcs[i] - oneIdcs[leftMost]);\n          leftMost++;\n          changes++;\n        } else {\n          break;\n        }\n      }\n      while ((tot == k) && (rightMost + 1 < m) && (i - leftMost) &&\n            (oneIdcs[rightMost + 1] - oneIdcs[i]) <\n             (oneIdcs[i] - oneIdcs[leftMost])) {\n        leftSum -= (oneIdcs[i] - oneIdcs[leftMost]);\n        leftMost++;\n        rightSum += (oneIdcs[rightMost + 1] - oneIdcs[i]);\n        rightMost++;\n      }\n      \n      long long moves = leftSum + rightSum + changes * 2;\n      if (tot == k) {\n        minMoves = (minMoves == -1) ? moves : min(minMoves, moves);\n      }\n      if (i + 1 < m) diff = oneIdcs[i + 1] - oneIdcs[i];\n    }\n    return minMoves;\n  }\n};\n```\nOne optimization could be to do away with the `oneIdcs` aray
[]