forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
39 lines (37 loc) · 1.14 KB
/
Solution.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
using System;
using System.Linq;
public class Solution {
public int MaximumGap(int[] nums) {
if (nums.Length < 2) return 0;
var max = nums.Max();
var min = nums.Min();
var bucketSize = Math.Max(1, (max - min) / (nums.Length - 1));
var buckets = new Tuple<int, int>[(max - min) / bucketSize + 1];
foreach (var num in nums)
{
var index = (num - min) / bucketSize;
if (buckets[index] == null)
{
buckets[index] = Tuple.Create(num, num);
}
else
{
buckets[index] = Tuple.Create(Math.Min(buckets[index].Item1, num), Math.Max(buckets[index].Item2, num));
}
}
var result = 0;
Tuple<int, int> lastBucket = null;
for (var i = 0; i < buckets.Length; ++i)
{
if (buckets[i] != null)
{
if (lastBucket != null)
{
result = Math.Max(result, buckets[i].Item1 - lastBucket.Item2);
}
lastBucket = buckets[i];
}
}
return result;
}
}