explained C++
consider all operation is to move \'1\', the cost of moving \'1\' from pos1 to pos2 is abs(pos1 - pos2).\nuse pos to record the positions of 1, pos[i] = the pos
consider all operation is to move \'1\', the cost of moving \'1\' from pos1 to pos2 is abs(pos1 - pos2).\nuse **pos** to record the positions of 1, *pos[i] = the position of the ith \'1\'*\n**cost of moving {pos[0]...pos[i]} to {0...i} = sum(pos[i] - i)**, using prefix sum\nuse a size **k** sliding window to traverse **pos**\nFind the median, the left part need to move right, and the right part need to move left, then use prefix sum to cal the cost.\n```\nclass Solution {\npublic:\n    int minMoves(vector<int>& nums, int k) {\n        int ret = INT_MAX;\n        vector<int> pos, left;\n        for (int i = 0; i < nums.size(); i++) {\n            left.push_back(pos.size());  //record the number of 1s in the left\n            if (nums[i] == 1) \n                pos.push_back(i); //record the positions of 1s\n        }\n        vector<int> prefix(pos.size(), 0);\n        for (int i = 0; i < pos.size(); i++) {\n            prefix[i] = pos[i] - i + (i > 0 ? prefix[i - 1] : 0); // the cost of moving {pos[0]...pos[i]} to {0...i};\n        }\n        int sum = 0, mid;\n        for (int i = 0; i + k <= pos.size(); i++) {\n            mid = pos[i + k/2]; //the median of the seq\n            \n            int l = left[mid]; // the number of 1s in the left is l\n            \n            //move {pos[i]...pos[l - 1]} to {??, mid - 1}, the cost = (mid - l) * size - (prefix[l - 1] - prefix[i - 1])\n            sum = (mid - l) * (l - i) - (l > 0 ? prefix[l - 1] : 0) + (i > 0 ? prefix[i - 1] : 0);\n            \n            //move {pos[l] ... pos[i + k - 1]} to {mid, ??}, the cost = (prefix[i + k - 1] - prefix[l - 1]) - (mid - l) * size\n            sum += (prefix[i + k - 1] - (l > 0 ? prefix[l - 1] : 0)) - (mid - l) * (i + k - l);\n            \n            ret = min(ret, sum);\n        }\n        return ret;\n    }\n};\n```
[]