g0101_0200.s0164_maximum_gap.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0164_maximum_gap;
// #Hard #Array #Sorting #Bucket_Sort #Radix_Sort
// #2022_06_25_Time_48_ms_(53.59%)_Space_84.1_MB_(20.66%)
import java.util.Arrays;
/**
* 164 - Maximum Gap\.
*
* Hard
*
* 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
**/
public class Solution {
public int maximumGap(int[] nums) {
if (nums.length < 2) {
return 0;
}
int ret = Integer.MIN_VALUE;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if ((nums[i + 1] - nums[i]) > ret) {
ret = (nums[i + 1] - nums[i]);
}
}
return ret;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy