问题描述:给定一个长度为 n 的 非空 整数数组,每次操作将会使 n - 1 个元素增加 1。找出让数组所有元素相等的最小操作次数。
示例:
输入:
[1,2,3]
输出:
3
解释:
只需要3次操作(注意每次操作会增加两个元素的值):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路: n-1个数同时加一,就好比每次有一个数自身减一,这样的话每个元素减去最小值求其和就是答案
public class Test01 {
public static void main(String[] args) {
int[] a = {1, 1, -2};
int b = maximumProduct(a);
System.out.println("====onlyqi:====="+b);
}
public static int maximumProduct(int[] nums) {
Arrays.sort(nums);
Integer min = nums[0];
Integer sum = 0;
for (int i = 1; i < nums.length; i++) {
sum = sum + nums[i] - min;
}
return sum;
}
}
输出结果:
我要刷100道算法题,第二道!!!