
Sponsored
Sponsored
The simplest approach to solve this problem is to first sort the array. Once sorted, the maximum gap will be found between consecutive elements. By iterating over the sorted array and computing the difference between each pair of consecutive elements, we can find the maximum difference.
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1) as no additional space is used except for variables.
1using System;
2
3public class Solution {
4 public int MaximumGap(int[] nums) {
5 if (nums.Length < 2) return 0;
6 Array.Sort(nums);
7 int maxGap = 0;
8 for (int i = 1; i < nums.Length; i++) {
9 maxGap = Math.Max(maxGap, nums[i] - nums[i - 1]);
10 }
11 return maxGap;
12 }
13}C#'s Array.Sort is used to sort the numbers. The algorithm then computes the maximum difference between consecutive sorted numbers.
This approach leverages the bucket sort idea to achieve linear time complexity. By calculating the bucket size and distributing array elements across buckets, we attempt to isolate maximum differences across distinct buckets, as adjacent elements within a bucket should have a smaller difference.
Time Complexity: O(n) since the bucket placement and scanning are linear operations.
Space Complexity: O(n) for the two bucket arrays.
1#
This C solution calculates the bucket size based on the range of numbers and the number of elements in the array. Elements are then placed into buckets which are used to determine the maximum gap between non-empty buckets.