-
Notifications
You must be signed in to change notification settings - Fork 112
/
1167-MinimumCostToConnectSticks.cs
52 lines (45 loc) · 1.36 KB
/
1167-MinimumCostToConnectSticks.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//-----------------------------------------------------------------------------
// Runtime: 372ms
// Memory Usage: 35.1 MB
// Link: https://leetcode.com/submissions/detail/369942316/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _1167_MinimumCostToConnectSticks
{
public int ConnectSticks(int[] sticks)
{
var pq = new SortedList<int, int>();
foreach (var stick in sticks)
{
if (pq.ContainsKey(stick))
pq[stick]++;
else
pq[stick] = 1;
}
int result = 0;
while (pq.Count > 1 || (pq.Count == 1 && pq.Values.First() > 1))
{
var x = pq.Keys.First();
if (pq[x] == 1)
pq.Remove(x);
else
pq[x]--;
var y = pq.Keys.First();
if (pq[y] == 1)
pq.Remove(y);
else
pq[y]--;
var cost = x + y;
result += cost;
if (pq.ContainsKey(cost))
pq[cost]++;
else
pq[cost] = 1;
}
return result;
}
}
}