1. Comparison Sort (Brute Force)
Intuition
Sort the array in ascending order and scan adjacent elements to find the maximum gap.
Algorithm
- 1. If nums.length < 2, return 0.
- 2. Sort nums in ascending order.
- 3. Loop i from 1 to N-1: - maxGap = max(maxGap, nums[i] - nums[i-1]).
- 4. Return maxGap.
All Pairs Intermediate Scan (O(N^3) Time)
2 of 2 questions left todayIn unsorted data, a pair is adjacent in sorted order if no other element falls strictly between them
In unsorted data, a pair is adjacent in sorted order if no other element falls strictly between them.
#include <iostream>#include <vector>#include <algorithm>using namespace std; // Brute Force Approach: Comparison Sortint maximumGap(vector<int>& nums) { if (nums.size() < 2) return 0; sort(nums.begin(), nums.end()); int maxGap = 0; for (int i = 1; i < nums.size(); i++) { maxGap = max(maxGap, nums[i] - nums[i - 1]); } return maxGap;} int main() { vector<int> nums = {3, 6, 9, 1}; int result = maximumGap(nums); cout << "Output: " << result << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting takes O(N log N). The linear difference scan takes O(N). - Space complexity:
O(1)— In-place sort takes O(1) auxiliary memory.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.