-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximumGap.py
More file actions
29 lines (24 loc) · 902 Bytes
/
maximumGap.py
File metadata and controls
29 lines (24 loc) · 902 Bytes
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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/maximum-gap/
# Author: Miao Zhang
# Date: 2021-01-24
class Solution:
def maximumGap(self, nums: List[int]) -> int:
max_gap = 0
if not nums or len(nums) < 2:
return max_gap
maxval = max(nums)
minval = min(nums)
each_bucket_len = (maxval - minval) // len(nums) + 1
buckets = [[] for _ in range((maxval - minval) // each_bucket_len + 1)]
for num in nums:
location = (num - minval) // each_bucket_len
buckets[location].append(num)
pre_max = float('inf')
for bucket in buckets:
if bucket and pre_max != float('inf'):
max_gap = max(max_gap, min(bucket) - pre_max)
if bucket:
pre_max = max(bucket)
return max_gap