Algorithm


Problem Name: 517. Super Washing Machines

You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.

For each move, you could 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.

Given an integer array machines 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. If it is not possible to do it, return -1.

 

Example 1:

Input: machines = [1,0,5]
Output: 3
Explanation:
1st move:    1     0 <-- 5    =>    1     1     4
2nd move:    1 <-- 1 <-- 4    =>    2     1     3
3rd move:    2     1 <-- 3    =>    2     2     2

Example 2:

Input: machines = [0,3,0]
Output: 2
Explanation:
1st move:    0 <-- 3     0    =>    1     2     0
2nd move:    1     2 --> 0    =>    1     1     1

Example 3:

Input: machines = [0,2,0]
Output: -1
Explanation:
It's impossible to make all three washing machines have the same number of dresses.

 

Constraints:

  • n == machines.length
  • 1 <= n <= 104
  • 0 <= machines[i] <= 105

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const findMinMoves = function(machines) {
  let total = 0
  for (let i of machines) total += i
  if (total % machines.length !== 0) return -1
  let avg = (total / machines.length) >> 0,
    cnt = 0,
    max = 0
  for (let load of machines) {
    cnt += load - avg
    max = Math.max(Math.max(max, Math.abs(cnt)), load - avg)
  }
  return max
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
machines = [1,0,5]

Output

x
+
cmd
3

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def findMinMoves(self, machines):
        target, n, sm, res, total = sum(machines) // len(machines), len(machines), 0, 0, sum(machines)
        if target * n != total: return -1
        for i in range(n):
            l, sm, r = target * i - sm, sm + machines[i], target * (n - i - 1) - total + sm + machines[i]
            res = max(res, l + r, l, r)
        return res
Copy The Code & Try With Live Editor

Input

x
+
cmd
machines = [1,0,5]

Output

x
+
cmd
3
Advertisements

Demonstration


Previous
#516 Leetcode Longest Palindromic Subsequence Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#518 Leetcode Coin Change II Solution in C, C++, Java, JavaScript, Python, C# Leetcode