✅Keep Track of Median in Variable Sliding Window || C++ ||
Code\n\n#define ll long long\n#define all(x) (x).begin(),(x).end()\n\nclass Solution {\npublic:\n    long long minimumMoves(vector<int>& nums, int k, int maxCha
# Code\n```\n#define ll long long\n#define all(x) (x).begin(),(x).end()\n\nclass Solution {\npublic:\n    long long minimumMoves(vector<int>& nums, int k, int maxChanges) {\n        ll n=nums.size();\n        vector<ll> cost(k+3,1e18);\n        ll pick=0;\n        for(int i=0 ; i<n ; i++){\n            ll nbr=0;\n            if((i-1)>=0 && nums[i-1]==1){\n                nbr++;\n            }\n            if((i+1)<n && nums[i+1]==1){\n                nbr++;\n            }\n            if(nums[i]){\n                cost[1]=min(cost[1],0LL);\n            }\n            if(nbr && nums[i]){\n                cost[2]=min(cost[2],1LL);\n            }\n            cost[nbr+nums[i]]=min(cost[nbr+nums[i]],nbr);\n        }\n        \n        //   !!!  -----------------      some critical cases    ------------------       !!!!\n        if(maxChanges>=k){\n            ll ans=(ll)k*2LL;\n            ans=min(ans,cost[1]+(k-1)*(2LL));\n            if(k>=2){\n                ans=min(ans,cost[2]+(k-2)*(2LL));\n            }\n            if(k>=3){\n                ans=min(ans,cost[3]+(k-3)*(2LL));\n            }\n            return ans;\n        }\n        \n        ll cst=1e18;\n        if((k-maxChanges)<=3){\n            cst=min(cst,2LL*(ll)maxChanges+cost[(k-maxChanges)]);\n            if(maxChanges>0 && (k-maxChanges+1)<=3){\n                cst=min(cst,2LL*(ll)(maxChanges-1)+cost[(k-maxChanges+1)]);\n            }\n            if(maxChanges>1 && (k-maxChanges+2)<=3){\n                cst=min(cst,2LL*(ll)(maxChanges-2)+cost[(k-maxChanges+2)]);\n            }\n        }\n        \n        //---------------------------------\n        \n        //keeping track of median in sliding window with cost to converge to median.....\n        ll xtra=k-maxChanges;\n        queue<ll> q;\n        queue<ll> md;\n        ll pref=0;\n        ll suff=0;\n        for(int i=0 ; i<n ; i++){\n            if(nums[i]==1){\n                q.push(i);\n                if(q.size()>=((xtra+1)/2)){\n                    md.push(i);\n                    suff+=i;\n                }\n                else{\n                    pref+=i;\n                }\n            }\n            while(q.size()>xtra){\n                pref-=q.front();\n                q.pop();\n                suff-=md.front();\n                pref+=md.front();\n                md.pop();\n            }\n            if(q.size()==xtra){\n                ll curr=2LL*(ll)(maxChanges)+(((ll)((xtra+1)/2)-1)*(ll)(md.front()))-pref+suff-( xtra - (((xtra+1)/2)-1))*(ll)md.front();\n                cst=min(cst,curr);\n            }\n        }\n        \n        \n        return cst;\n        \n    }\n};\n```
['Sliding Window', 'C++']