首页 > 代码库 > LeetCode 453. Minimum Moves to Equal Array Elements C#
LeetCode 453. Minimum Moves to Equal Array Elements C#
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Solution:
incrementing n-1 elements by one, means every time need to increment 1 to every number except the maximum. but it‘s hard to implement.
Increment to every nums except max, is as same as decrement 1 on one number until every number equals min number.
1 public class Solution { 2 public int MinMoves(int[] nums) { 3 if(nums.Length==0) 4 { 5 return 0; 6 } 7 int n = nums.Length; 8 //Find min value in nums; 9 int min =nums[0]; 10 foreach(int num in nums) 11 { 12 min = Math.Min(min, num); 13 } 14 15 //calculate the difference of every num from nums and min; ths sum should be the min Moves 16 //add 1 to n-1 is same as minus 1 from the max each time. 17 int moves = 0; 18 foreach(int num in nums) 19 { 20 moves +=(num-min); 21 } 22 return moves; 23 } 24 }
LeetCode 453. Minimum Moves to Equal Array Elements C#
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。