1194. Super Washing Machines

Code(Language:C++)
class Solution {
public:
    /**
     * @param machines: an integer array representing the number of dresses in each washing machine from left to right on the line
     * @return: the minimum number of moves to make all the washing machines have the same number of dresses
     */
    int findMinMoves(vector<int> &machines) {
        // Write your code here
        // greedy 解法
        int sum = 0;
        const int size = machines.size(); 
        for(int i : machines){
            sum += i; 
        }
        if(sum % size){
            return -1; 
        }
        int avg = sum / size; 
        int res = 0, cnt = 0;  
        for(int i : machines){
            cnt += i - avg; 
            res = max(max(res, abs(cnt)), abs(i - avg)); 
        }
        return res; 
    }
};

Comments

Popular posts from this blog

算法的比较