-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
37 lines (36 loc) · 973 Bytes
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Linq;
namespace MinimumMovesToEqualArrayElementsII
{
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4 };
Console.WriteLine(MinMoves2(nums));
}
static int MinMoves2(int[] nums)
{
Array.Sort(nums);
int sum = nums.Sum(n => n);
int res = 0;
int index = nums.Length / 2;
if (nums.Length % 2 == 0)
{
int t1 = nums[index];
int t2 = nums[index - 1];
res = Math.Min(GetStep(nums, t1), GetStep(nums, t2));
}
else
res = GetStep(nums, nums[index]);
return res;
}
static int GetStep(int[] nums, int target)
{
int step = 0;
foreach (var n in nums)
step += Math.Abs(n - target);
return step;
}
}
}