- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of Java from the credited upstream file 164.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Bucket {2 public int mn;3 public int mx;4 public Bucket(int mn, int mx) {5 this.mn = mn;6 this.mx = mx;7 }8}9 10class Solution {11 public int maximumGap(int[] nums) {12 if (nums.length < 2)13 return 0;14 15 final int mn = Arrays.stream(nums).min().getAsInt();16 final int mx = Arrays.stream(nums).max().getAsInt();17 if (mn == mx)18 return 0;19 20 final int gap = (int) Math.ceil((double) (mx - mn) / (nums.length - 1));21 final int bucketsLength = (mx - mn) / gap + 1;22 Bucket[] buckets = new Bucket[bucketsLength];23 24 for (int i = 0; i < buckets.length; ++i)25 buckets[i] = new Bucket(Integer.MAX_VALUE, Integer.MIN_VALUE);26 27 for (final int num : nums) {28 final int i = (num - mn) / gap;29 buckets[i].mn = Math.min(buckets[i].mn, num);30 buckets[i].mx = Math.max(buckets[i].mx, num);31 }32 33 int ans = 0;34 int prevMax = mn;35 36 for (final Bucket bucket : buckets) {37 if (bucket.mn == Integer.MAX_VALUE) 38 continue;39 ans = Math.max(ans, bucket.mn - prevMax);40 prevMax = bucket.mx;41 }42 43 return ans;44 }45}46