Bucketing! A lot of details to take care.
struct Bucket { Bucket() :l(-1), r(-1), bValid(false){}; int l, r; bool bValid; }; class Solution { public: /** * @param nums: a vector of integers * @return: the maximum difference */ int maximumGap(vector<int> nums) { // Remove duplicates unordered_set<int> hs(nums.begin(), nums.end()); nums.assign(hs.begin(), hs.end()); // size_t n = nums.size(); if (n < 2) return 0; long long mn = *min_element(nums.begin(), nums.end()); long long mx = *max_element(nums.begin(), nums.end()); if (mn == mx) return 0; // Set up buckets vector<Bucket> bk(n); long long interval = (mx - mn + 1) / (long long)(n - 1); for (auto v : nums) { int binx = (v - mn) / interval; bk[binx].l = (!bk[binx].bValid) ? v : min(bk[binx].l, v); bk[binx].r = (!bk[binx].bValid) ? v : max(bk[binx].r, v); bk[binx].bValid = true; } // Go check bucket by bucket int i = 0, ret = 0; while (i < bk.size()) { if (bk[i].bValid) { int wi = bk[i].r - bk[i].l, wo = 0; int j = i + 1; while (j < bk.size() && !bk[j].bValid) j++; if (j < bk.size()) wo = bk[j].l - bk[i].r; ret = max(ret, max(wi, wo)); i = j; } else i++; } return ret; } };