AlgoMaster Logo

Maximum Gap

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Simple Sort and Compare

Intuition:

The simplest way to solve this problem is to sort the array and then find the maximum gap between successive elements. Although this is not the most optimal solution in terms of time complexity, it is straightforward to implement and understand.

Steps:

  1. Sort the given array.
  2. Initialize a variable maxGap to store the maximum difference found.
  3. Iterate through the sorted array and calculate the difference between successive elements.
  4. Update maxGap if a larger difference is found.

Code:

2. Bucket Sort

Intuition:

To achieve a better time complexity, we can use a bucket sort method. The core idea is distributing the numbers into buckets such that each bucket holds a range of numbers. We calculate the maximum possible difference, which ensures that the maximum gap cannot be confined within a single bucket but must be between the maximum of one bucket and the minimum of the next.

Steps:

  1. Find the minimum and maximum elements in the array.
  2. Calculate the gap size, which is the ceiling value of (max - min) / (n - 1).
  3. Create buckets that will store only the minimum and maximum values that fall into them.
  4. Iterate through each number to place it in the right bucket by calculating the appropriate index.
  5. Finally, iterate through the buckets to calculate the maximum gap between the maximum value of the current non-empty bucket and the minimum value of the next non-empty bucket.

Code: