You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
832 B

2 years ago
package class13;
// 本题测试链接 : https://leetcode.com/problems/super-washing-machines/
public class Code02_SuperWashingMachines {
public static int findMinMoves(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
int size = arr.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
if (sum % size != 0) {
return -1;
}
int avg = sum / size;
int leftSum = 0;
int ans = 0;
for (int i = 0; i < arr.length; i++) {
int leftRest = leftSum - i * avg;
int rightRest = (sum - leftSum - arr[i]) - (size - i - 1) * avg;
if (leftRest < 0 && rightRest < 0) {
ans = Math.max(ans, Math.abs(leftRest) + Math.abs(rightRest));
} else {
ans = Math.max(ans, Math.max(Math.abs(leftRest), Math.abs(rightRest)));
}
leftSum += arr[i];
}
return ans;
}
}