LC.P517[超级洗衣机]

方法一:贪心

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int findMinMoves(int[] machines) {
int sum = 0, n = machines.length;
for (int x : machines) {
sum += x;
}
if (sum % n != 0) return -1;
int ans = 0, cnt = 0, avg = sum / n;
for (int x : machines) {
x -= avg;
cnt += x;
ans = Math.max(ans, Math.max(x, Math.abs(cnt)));
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$