Skip to content

Commit 58a3a49

Browse files
committed
Create maximum-gap.py
1 parent ab27e5b commit 58a3a49

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Python/maximum-gap.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution:
5+
# @param numss: a list of integers
6+
# @return: the maximum difference
7+
def maximumGap(self, nums):
8+
if len(nums) < 2:
9+
return 0
10+
11+
# Init bucket.
12+
max_val, min_val = max(nums), min(nums)
13+
gap = max(1, (max_val - min_val) / (len(nums) - 1))
14+
bucket_size = (max_val - min_val) / gap + 1
15+
bucket = [{'min':float("inf"), 'max':float("-inf")} \
16+
for _ in xrange(bucket_size)]
17+
18+
# Find the bucket where the n should be put.
19+
for n in nums:
20+
# min_val / max_val is in the first / last bucket.
21+
if n in (max_val, min_val):
22+
continue
23+
i = (n - min_val) / gap
24+
bucket[i]['min'] = min(bucket[i]['min'], n)
25+
bucket[i]['max'] = max(bucket[i]['max'], n)
26+
27+
# Count each bucket gap between the first and the last bucket.
28+
max_gap, pre_bucket_max = 0, min_val
29+
for i in xrange(bucket_size):
30+
# Skip the bucket it empty.
31+
if bucket[i]['min'] == float("inf") and \
32+
bucket[i]['max'] == float("-inf"):
33+
continue
34+
max_gap = max(max_gap, bucket[i]['min'] - pre_bucket_max)
35+
pre_bucket_max = bucket[i]['max']
36+
# Count the last bucket.
37+
max_gap = max(max_gap, max_val - pre_bucket_max)
38+
39+
return max_gap

0 commit comments

Comments
 (0)