#include #include using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 10000000 struct absolute_minima{ using ll = long long; priority_queue> pQ; priority_queue,vector>,greater>> sQ; ll pSum=0,sSum=0,pCnt=0,sCnt=0; void add(long long x,long long w){ sQ.emplace(x,w); sSum += x*w; sCnt += w; while(true){ if(pQ.size()>0&&sQ.size()>0){ if(pQ.top().first>sQ.top().first){ move(pCnt > sCnt); continue; } else if(pCnt > sCnt){ move(true); continue; } else if(pCnt + sQ.top().second <= sCnt - sQ.top().second){ move(false); continue; } } else{ if(sQ.size()==0){ move(true); continue; } else{ if(sQ.top().second <= sCnt - sQ.top().second){ move(false); continue; } } } break; } } void add(ll x){ add(x,1LL); } ll median(){ return sQ.top().first; } vector medians(){ vector ret; if((pCnt+sCnt)%2==0){ if(pCnt==sCnt)ret.push_back(pQ.top().first); else ret.push_back(sQ.top().first); } ret.push_back(median()); return ret; } ll distance_sum(){ ll ret = 0LL; ret -= pSum; ret += sSum; ret += pCnt * median(); ret -= sCnt * median(); return ret; } void move(bool f){ if(f){ if(pQ.size()>0){ pair p = pQ.top(); pQ.pop(); pSum -= p.first*p.second; pCnt -= p.second; sQ.push(p); sSum += p.first*p.second; sCnt += p.second; } } else{ if(sQ.size()>0){ pair p = sQ.top(); sQ.pop(); sSum -= p.first*p.second; sCnt -= p.second; pQ.push(p); pSum += p.first*p.second; pCnt += p.second; } } } }; int main(){ int N; cin>>N; set S; vector A(N); rep(i,N){ int x; scanf("%d",&x); A[i] = x; S.insert(x); } if(S.size()==1)cout<<1< S1(N,0),S2(N,0); { absolute_minima X; rep(i,N){ X.add(A[i]); S1[i] = X.distance_sum(); } } { absolute_minima X; for(int i=N-1;i>=0;i--){ X.add(A[i]); S2[i] = X.distance_sum(); } } long long ans = 1e18; rep(i,N-1){ ans = min(ans,S1[i] + S2[i+1]); } cout<