Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Before we dive into the problem-solving approach, let me ask a few clarifying questions:
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
class Solution {
public:
int maximumGap(std::vector<int>& nums) {
int n = nums.size();
if (n < 2) return 0;
int minVal = *min_element(nums.begin(), nums.end());
int maxVal = *max_element(nums.begin(), nums.end());
// Edge case: all elements are the same
if (minVal == maxVal) return 0;
// Calculate the size of the bucket
int bucketSize = std::max(1, (maxVal - minVal) / (n - 1));
int bucketCount = (maxVal - minVal) / bucketSize + 1;
std::vector<int> bucketMin(bucketCount, INT_MAX);
std::vector<int> bucketMax(bucketCount, INT_MIN);
// Place each number in its corresponding bucket
for (int num : nums) {
int bucketIndex = (num - minVal) / bucketSize;
bucketMin[bucketIndex] = std::min(bucketMin[bucketIndex], num);
bucketMax[bucketIndex] = std::max(bucketMax[bucketIndex], num);
}
// Calculate the maximum gap
int maxGap = 0, prevMax = minVal;
for (int i = 0; i < bucketCount; ++i) {
if (bucketMin[i] == INT_MAX) continue; // skip empty buckets
maxGap = std::max(maxGap, bucketMin[i] - prevMax);
prevMax = bucketMax[i];
}
return maxGap;
}
};
int main() {
Solution sol;
std::vector<int> nums = {3, 6, 9, 1};
std::cout << sol.maximumGap(nums) << std::endl; // Output should be 3
return 0;
}
Hence, the overall time complexity is (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?