Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Arrays

Maximum Gap

Hard · Arrays · Asked at Amazon, Google, Microsoft

Print the largest difference between two successive elements of the array after sorting it. If the array has fewer than two elements, print 0. Try to do it in linear time.

Input

First line: n. Second line: n space-separated integers.

Output

The maximum gap.

Constraints

Pigeonhole: with n numbers between min and max, the maximum gap is at least (max − min) / (n − 1). Make n − 1 buckets of that width and keep only each bucket’s min and max — the answer is always between neighbouring non-empty buckets, never inside one.

Example 1

Input

4
3 6 9 1

Output

3

Example 2

Input

1
10

Output

0

Hints

  1. Sorting gives the answer in O(n log n), but O(n) is possible.
  2. The maximum gap is at least (max − min) / (n − 1) — the average gap.
  3. So a gap inside a bucket of that width can never be the answer; only gaps between buckets matter.

Approach

If n < 2 or all values are equal, print 0. Otherwise use bucket width w = max(1, (max − min) / (n − 1)) and (max − min) / w + 1 buckets, storing only each bucket’s minimum and maximum. Walk the non-empty buckets in order; the answer is the largest (bucket min − previous bucket max). Every element is placed in O(1), so the whole thing is linear.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<long long> a(n);
    for (auto &x : a) cin >> x;
    long long lo = *min_element(a.begin(), a.end()), hi = *max_element(a.begin(), a.end());
    if (n < 2 || lo == hi) {
        cout << 0 << "\n";
        return 0;
    }
    long long w = max(1LL, (hi - lo) / (n - 1));
    int cnt = (hi - lo) / w + 1;
    vector<long long> bmin(cnt, LLONG_MAX), bmax(cnt, LLONG_MIN);
    for (long long x : a) {
        int b = (x - lo) / w;
        bmin[b] = min(bmin[b], x);
        bmax[b] = max(bmax[b], x);
    }
    long long best = 0, prev = lo;
    for (int b = 0; b < cnt; b++) {
        if (bmin[b] == LLONG_MAX) continue;
        best = max(best, bmin[b] - prev);
        prev = bmax[b];
    }
    cout << best << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
lo, hi = min(a), max(a)
if n < 2 or lo == hi:
    print(0)
else:
    w = max(1, (hi - lo) // (n - 1))
    cnt = (hi - lo) // w + 1
    bmin = [None] * cnt
    bmax = [None] * cnt
    for x in a:
        b = (x - lo) // w
        if bmin[b] is None or x < bmin[b]:
            bmin[b] = x
        if bmax[b] is None or x > bmax[b]:
            bmax[b] = x
    best, prev = 0, lo
    for b in range(cnt):
        if bmin[b] is None:
            continue
        best = max(best, bmin[b] - prev)
        prev = bmax[b]
    print(best)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[] a = new long[n];
        long lo = Long.MAX_VALUE, hi = Long.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
            lo = Math.min(lo, a[i]);
            hi = Math.max(hi, a[i]);
        }
        if (n < 2 || lo == hi) {
            System.out.println(0);
            return;
        }
        long w = Math.max(1, (hi - lo) / (n - 1));
        int cnt = (int) ((hi - lo) / w + 1);
        long[] bmin = new long[cnt], bmax = new long[cnt];
        Arrays.fill(bmin, Long.MAX_VALUE);
        Arrays.fill(bmax, Long.MIN_VALUE);
        for (long x : a) {
            int b = (int) ((x - lo) / w);
            bmin[b] = Math.min(bmin[b], x);
            bmax[b] = Math.max(bmax[b], x);
        }
        long best = 0, prev = lo;
        for (int b = 0; b < cnt; b++) {
            if (bmin[b] == Long.MAX_VALUE) continue;
            best = Math.max(best, bmin[b] - prev);
            prev = bmax[b];
        }
        System.out.println(best);
    }
}

Solve Maximum Gap online · All practice problems