-
Notifications
You must be signed in to change notification settings - Fork 112
/
1046-LastStoneWeight.cs
60 lines (56 loc) · 1.77 KB
/
1046-LastStoneWeight.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
53
54
55
56
57
58
59
60
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 24.2 MB
// Link: https://leetcode.com/submissions/detail/323881103/
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _1046_LastStoneWeight
{
public int LastStoneWeight(int[] stones)
{
var counts = new int[1001];
var maxWeight = int.MinValue;
foreach (var stone in stones)
{
counts[stone]++;
maxWeight = Math.Max(maxWeight, stone);
}
var biggestWeight = 0;
var currentWeight = maxWeight;
while (currentWeight > 0)
{
if (counts[currentWeight] == 0)
{
currentWeight--;
continue;
}
if (biggestWeight == 0)
{
counts[currentWeight] %= 2;
if (counts[currentWeight] == 1)
{
biggestWeight = currentWeight;
counts[currentWeight] = 0;
}
currentWeight--;
}
else
{
counts[currentWeight]--;
if (biggestWeight - currentWeight <= currentWeight)
{
counts[biggestWeight - currentWeight]++;
biggestWeight = 0;
}
else
{
biggestWeight -= currentWeight;
}
}
}
return biggestWeight;
}
}
}