Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 

Try to solve it in linear time/space. 

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

In order to solve this in linear time, we cannot use general sorting algorithm. Here we use bucket sort.

  • First, we scan the array to find the min and the max values.  
  • We can then create n - 1 buckets with equal size. Suppose we have n elements in total, then we have n - 2 elements except the min and the max. Scan the array again to put the n - 2 elements into these buckets. We should have at least one empty bucket. For each bucket, we record the min and the max for all the elements within that bucket. 
  • Finally, we scan all the buckets, and maintain the maximum gap. Note that the maximum gap between the successive elements in the sorted array can only be the gap between buckets. Why? Try to consider the size of each bucket.
Therefore, the total time complexity is O(3n) and the space complexity is O(2n).

Comments

  1. maxdiff = max(maxdiff, it.first - lastval); would you explain this? I am understanding, in each bucket, first is min, second is max, so in order to get max gap, you would like to do it.second - lastMin, but here it looks like you are doing it.first - lastMax. Why?

    ReplyDelete
    Replies
    1. Note that the size of each bucket is (max - min) / (n - 1), which is less than or equal to the maximum gap (since we have n - 1 gaps for n numbers, and the total length is max - min). Therefore, the maximum gap can only be the gap between the maximum element in the i-th bucket and the minimum element in the (i+1)-th bucket.

      Delete
    2. An example is, [4, 1, 8, 3, 10, 7]
      min is 1 and max is 10, the gap is 9/5 = 1.8
      so the five buckets are
      [1, 2.8), is empty (since 1 is minimum and has been ignored)
      [2.8, 4.6), min is 3 and max is 4
      [4.6, 6.4), is empty
      [6.4, 8.2), min is 7 and max is 8
      [8.2, 10), is empty

      Then we scan these buckets again. If we ignore the empty buckets, it makes sense to compare the following gaps:
      3 (min of the second bucket) - 1 (minimum in total)
      7 (min of the fourth bucket) - 4 (max of the second bucket)
      10 (maximum in total) - 8 (max of the fourth bucket)

      and we found that the maximum gap is 3.

      Delete

Post a Comment

Popular posts from this blog

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design