# Super Washing Machines in C++

C++Server Side ProgrammingProgramming

Suppose we have n super washing machines on a row. Initially, each washing machine has some dresses or empty. Now, for each move, we can choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Suppose we have one integer array representing the number of dresses in each washing machine from left to right on the row, we should find the minimum number of moves to make all the washing machines have the same number of clothes. If it is not possible to do, then return -1.

So when the input is like [1,0,5], then the output will be 3, this is because send 5 to 0, so the distribution will be [1, 1, 4], then middle 1 to left one, 4 to 1, then it will be [2,1,3], then 2 to 1, so finally it will be [2,2,2]

To solve this, we will follow these steps −

• sum := sum of all elements of v
• n := size of v
• if sum mod n is not equal to 0, then −
• return -1
• req := sum / n, ret := 0, extra := 0
• for initialize i := 0, when i < n, update (increase i by 1), do −
• x := v[i]
• extra := extra + (x - req)
• ret := maximum of {ret, x - req, |extra|
• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMinMoves(vector<int>& v) {
int sum = accumulate(v.begin(), v.end(), 0);
int n = v.size();
if(sum % n != 0) return -1;
int req = sum / n;
int ret = 0;
int extra = 0;
for(int i = 0; i < n; i++){
int x = v[i];
extra +=( x - req);
ret = max({ret, x - req, abs(extra)});
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {2,1,6};
cout << (ob.findMinMoves(v));
}

## Input

{2,1,6}

## Output

3
Updated on 01-Jun-2020 11:31:06