Long story short, the other day I discovered the site LeetCode and started solving some of its problems until I stumbled onto this one.
I'll paste the description here:
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.
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]
The problem is, the solution I am trying to submit always exceeds the allowed processing time limit and I feel like I've reached a dead end. Can anyone suggest a way to improve my code?
static void Main()
{
int res = MinMoves(new int[] { 1, 2, 3 });
}
public static int MinMoves(int[] nums)
{
if (nums.Length < 2)
return 0;
int moves = 0;
int diff = 0;
int min = 0;
int max = 0;
int maxIX = 0;
do
{
min = nums.Min();
max = nums.Max();
maxIX = Array.IndexOf(nums, max);
diff = Math.Abs(max - min);
moves += diff;
for (int i = 0; i < nums.Length; i++)
if (i != maxIX)
nums[i] += diff;
} while (min != max);
return moves;
}