当前位置:网站首页>Leetcode- minimum number of operations to make array elements equal - simple

Leetcode- minimum number of operations to make array elements equal - simple

2022-06-13 05:49:00 AnWenRen

title :453 The minimum number of operations makes the array elements equal - Simple

subject

Give you a length of n Array of integers for , Each operation will make n - 1 Elements added 1 . Returns the minimum number of operations to make all elements of the array equal .

Example 1

 Input :nums = [1,2,3]
 Output :3
 explain :
 It only needs 3 operations ( Note that each operation increases the value of two elements ):
[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

Example 2

 Input :nums = [1,1,1]
 Output :0

Tips

n == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
The answer is guaranteed 32-bit Integers

Code Java

public int minMoves1(int[] nums) {
    
    //  New knowledge  Stream  aggregate   Array   You can use   Be similar to   iterator  Iterator
    int min_value = Arrays.stream(nums).min().getAsInt();
    int sum = 0;
    for (int num : nums) {
    
        sum += num - min_value;
    }
    return sum;
}
原网站

版权声明
本文为[AnWenRen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280507175780.html