LeetCode 0164. Maximum Gap Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0164. Maximum Gap

Description

Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.

You must write an algorithm that runs in linear time and uses linear extra space.

 

Example 1:

Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.

Example 2:

Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109

Solutions

Solution 1: Discuss Different Cases

Let m represent the length of string s, and n represent the length of string t. We can assume that m is always greater than or equal to n.

If m-n > 1, return false directly;

Otherwise, iterate through s and t, if s[i] is not equal to t[i]:

  • If m ≠ n, compare s[i+1:] with t[i:], return true if they are equal, otherwise return false;
  • If m = n, compare s[i:] with t[i:], return true if they are equal, otherwise return false.

If the iteration ends, it means that all the characters of s and t that have been iterated are equal, at this time it needs to satisfy m=n+1.

The time complexity is O(m), where m is the length of string s. The space complexity is O(1).

PythonJavaC++GoC#
class Solution: def maximumGap(self, nums: List[int]) -> int: n = len(nums) if n < 2: return 0 mi, mx = min(nums), max(nums) bucket_size = max(1, (mx - mi) // (n - 1)) bucket_count = (mx - mi) // bucket_size + 1 buckets = [[inf, -inf] for _ in range(bucket_count)] for v in nums: i = (v - mi) // bucket_size buckets[i][0] = min(buckets[i][0], v) buckets[i][1] = max(buckets[i][1], v) ans = 0 prev = inf for curmin, curmax in buckets: if curmin > curmax: continue ans = max(ans, curmin - prev) prev = curmax return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !