Show problems as
Classic problem #164MediumArraySortingBucket SortRadix SortPigeonhole Principle

Maximum Gap

Real-world version: Widest Step Between Sorted Readings
Tracked in this browser only
Read Maximum Gap on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A logger dumps nums, a batch of meter readings in the order they were captured, so the batch is in no particular order and readings may repeat.

Imagine the batch laid out on a number line from smallest to largest. Between each neighbouring pair of that laid-out sequence there is a step, and the step is the difference between the two values. Return the width of the widest step. When the batch holds fewer than two readings there is no step at all, so return 0.

Solve it in time that grows linearly with the number of readings, using extra space that also grows only linearly.

Examples

Example 1

Input
nums = [3, 41, 7, 20]
Output
21

Laid out the readings run 3, 7, 20, 41, so the steps are 4, 13 and 21 and the widest is 21.

Example 2

Input
nums = [7, 7, 1]
Output
6

Laid out the readings run 1, 7, 7, giving steps of 6 and 0, so the widest step is 6.

Example 3

Input
nums = [9]
Output
0

A single reading leaves no neighbouring pair, so the answer is 0.

Example 4

Input
nums = [5, 5, 5]
Output
0

All three readings match, so every step is 0.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def widest_reading_step(readings: list[int]) -> int:
Java
public int widestReadingStep(int[] readings)