Simple Code with Explanation


  • 0
    O
    class Solution {
        /*
            machine[0], machine[1],,,[i-1],[i],[i+1],,,[n-1]
                                          ^   
                                          |   
                                          l   
            l: number of clothes required to move between left and right
        */
    public:
        int findMinMoves(vector<int>& m) {
            int n = m.size(), move = 0;
            for (int i = 1; i < n; i++)
                m[i] += m[i - 1];
            
            if (m.back() % n != 0)
                return -1;
                
            for (int i = 1, avg = m.back() / n; i < n; i++) {
                int l = abs(m[i - 1] - avg * i);
                int offload = m[i] - m[i - 1] - avg;
                move = max(move, max(l, offload));
            }
            return move;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.