LeetCode:453. Minimum Moves to Equal Array Elements
1 package Today; 2 //LeetCode:453. Minimum Moves to Equal Array Elements 3 /* 4 Given a non-empty integer array of size n, find the minimum number of moves required to make all array 5 elements equal, where a move is incrementing n - 1 elements by 1. 6 7 Example: 8 Input: 9 [1,2,3] 10 Output: 11 3 12 Explanation: 13 Only three moves are needed (remember each move increments two elements): 14 [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 15 */ 16 public class minMoves453 { 17 public static int minMoves(int[] nums) { 18 int min=nums[0]; 19 int sum=0; 20 for(int i=1;i<nums.length;i++){ 21 if(nums[i]<min) 22 min=nums[i]; 23 } 24 for(int i=0;i<nums.length;i++){ 25 sum+=nums[i]-min; 26 } 27 return sum; 28 } 29 public static void main(String[] args) { 30 // TODO Auto-generated method stub 31 int[] nums={1,2,3}; 32 int[] nums2={1,2,4,6}; 33 System.out.println(minMoves(nums)); 34 System.out.println(minMoves(nums2)); 35 } 36 37 }