Super Washing Machines — LeetCode 517 Python Solution
HardGreedyArray
- Problem
- #517
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.
Example
- Input
- machines = [1,0,5]
- Output
- 3
- Explanation
- 1st move: 1 0 <-- 5 => 1 1 4
Python solution
Python
class Solution:
def findMinMoves(self, machines: List[int]) -> int:
n = len(machines)
k, mod = divmod(sum(machines), n)
if mod:
return -1
ans = s = 0
for x in machines:
x -= k
s += x
ans = max(ans, abs(s), x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of washing machines |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 517. Super Washing Machines is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 517. Super Washing Machines?
- LeetCode 517. Super Washing Machines is rated Hard on LeetCode.
- What is the time complexity of LeetCode 517. Super Washing Machines?
- The Python solution on this page runs in O(n), where n is the number of washing machines.
- What is the space complexity of LeetCode 517. Super Washing Machines?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 517. Super Washing Machines cover?
- LeetCode 517. Super Washing Machines is tagged Greedy and Array on LeetCode.