Easy understand solution O(n) time and O(1) space


  • 10

    toLeft: the number of cloths moved to left from this machine
    toRight: the number of cloths moved to right from this machine
    toLeft and toRight may be negative but it's okay.

    def findMinMoves(self, machines):
        if sum(machines) % len(machines) == 0:
            target = sum(machines) / len(machines)
        else:
            return -1
        toLeft = 0
        res = 0
        for i in range(len(machines)):
            toRight =  machines[i]- target - toLeft
            res = max(res, toLeft, toRight, toLeft + toRight)
            toLeft = -toRight
        return res

  • 0
    A

    @lee215 Could you please explain the thought behind this :
    res = max(res, toLeft, toRight, toLeft + toRight)

    thanks :)


Log in to reply
 

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