Skip to content

Commit 071a707

Browse files
committed
Maximum Gap
1 parent 41bd6c9 commit 071a707

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

164 Maximum Gap.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
3+
4+
Try to solve it in linear time/space.
5+
6+
Return 0 if the array contains less than 2 elements.
7+
8+
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
9+
'''
10+
11+
class Solution(object):
12+
def maximumGap(self, nums):
13+
"""
14+
:type nums: List[int]
15+
:rtype: int
16+
"""
17+
18+
def radix_sort(nums):
19+
max_num = max(nums)
20+
i = 1
21+
while max_num // i:
22+
buckets = [[] for __ in range(10)]
23+
for num in nums:
24+
buckets[((num // i) % 10)].append(num)
25+
nums = [num for bucket in buckets for num in bucket]
26+
i *= 10
27+
return nums
28+
29+
n = len(nums)
30+
if n < 2:
31+
return 0
32+
nums = radix_sort(nums)
33+
print(nums)
34+
max_gap = 0
35+
for i in range(1, n):
36+
max_gap = max(max_gap, nums[i] - nums[i - 1])
37+
return max_gap
38+
39+
40+
if __name__ == "__main__":
41+
assert Solution().maximumGap([99, 50, 3, 18, 28]) == 49

0 commit comments

Comments
 (0)