Friday, February 13, 2015

Maximum Gap -- LeetCode

[Question]
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.

[Analysis]
The problem can be solved by sorting the array first. However, it won't be linear time.
The maximum difference between the successive elements in sorted array, must be larger than (max-min)/ (N-1), where N is the number of elements in the array. Therefore, we can use "bucket sort" and distribute elements into N-1 buckets, whose size is (max-min)/(N-1). The maximum difference between successive elements must be in different buckets. Each bucket needs to store only its the minimal and maximal elements. In this way, the time complexity is O(N).

[Solution]
class Solution {
public:
    int maximumGap(vector<int> &num) {
        if (num.size()<2) return 0;
        if (num.size()==2) return max(num[0], num[1]) - min(num[0], num[1]);
     
        int num_min = *min_element(num.begin(), num.end());
        int num_max = *max_element(num.begin(), num.end());
        int len = (num_max - num_min) / (num.size() - 1) +1; // need ceiling of value;
     
        vector<pair<int, int>> buckets (num.size(), pair<int, int> (INT_MAX, INT_MIN));
     
        for (auto n: num) {
            int index = (n-num_min) / len;
            buckets[index].first = min (buckets[index].first, n);
            buckets[index].second = max(buckets[index].second, n);
        }
     
        int gap = 0;
        int prev = buckets[0].second;
        for (int i=1; i<buckets.size(); i++) {
            if (prev!=INT_MIN && buckets[i].first!=INT_MAX) {
                gap = max(gap, buckets[i].first - prev);
                prev = buckets[i].second;
            }
        }
        return gap;
    }
};

No comments:

Post a Comment