702710. Maximum Gap

Easy

Maximum Gap

Slug: maximum-gap3845

Difficulty: Easy

Id: 702710

Topic Tags: Arrays, Data Structures

Company Tags: HunanAsset

Summary

Given an array of n integers, find the maximum gap between two consecutive numbers. The problem is about finding the largest difference between any pair of adjacent elements in the array.

Detailed Explanation

The approach to solve this problem involves iterating through the array and maintaining the minimum and maximum values seen so far. For each element, we update the minimum and maximum values if necessary. Then, we calculate the gap by subtracting the previous maximum value from the current minimum value. We keep track of the maximum gap found so far.

Here's a step-by-step breakdown of the solution:

  1. Initialize maxSoFar to negative infinity and minSoFar to positive infinity.
  2. Iterate through the array:
    • For each element, update minSoFar if it is smaller than the current minimum value.
    • Update maxSoFar if it is larger than the current maximum value.
  3. Calculate the gap by subtracting maxSoFar from minSoFar.
  4. Keep track of the maximum gap found so far.

Time complexity: O(n), where n is the number of elements in the array. This is because we are iterating through the array once.

Space complexity: O(1), as we are only using a constant amount of space to store the minimum and maximum values.

Here's an ASCII art diagram illustrating the step-by-step process:

  +---------------+
  |  arr  |
  +---------------+
           |
           |
           v
  +---------------+
  |  minSoFar  | maxSoFar
  +---------------+
           |
           |
           v
  Gap = maxSoFar - minSoFar
  Update maxSoFar and minSoFar as needed

Optimized Solutions

Java

View on GeeksforGeeks
public int maximumGap(int[] arr) {
    if (arr.length < 2) return 0;
    
    int n = arr.length;
    int[] minArr = new int[n];
    int[] maxArr = new int[n];
    
    for (int i = 0; i < n; i++) {
        minArr[i] = arr[i];
        maxArr[i] = arr[i];
    }
    
    for (int i = 1; i < n; i++) {
        if (arr[i] < minArr[i-1]) minArr[i] = arr[i];
        if (arr[i] > maxArr[i-1]) maxArr[i] = arr[i];
    }
    
    int maxGap = 0;
    for (int i = 1; i < n; i++) {
        maxGap = Math.max(maxGap, maxArr[i-1]-minArr[i]);
    }
    
    return maxGap;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.