703166. Race in Fooland

Easy

Race in Fooland

Summary

In this problem, we are given an array of N integers and our task is to find out which pair of elements has the maximum difference. The input array represents a race track and each integer represents the position of a runner on the track. Our goal is to identify the pair of runners that have the maximum distance between them.

Detailed Explanation

The approach to solve this problem is quite simple. We can sort the given array in ascending order. Then, we iterate through the sorted array from both ends (i.e., from the start and end) and calculate the difference between each pair of elements. The maximum difference found so far will be our answer.

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

  1. Sort the input array in ascending order.
  2. Initialize two pointers, one at the start of the array (i.e., left = 0) and another at the end of the array (i.e., right = N-1).
  3. Calculate the difference between the elements at the left and right indices (diff = arr[left] - arr[right]).
  4. Compare this difference with our current maximum difference (max_diff). If it's greater, update max_diff.
  5. Move the pointers towards each other based on the comparison:
    • If arr[left] < arr[right], move the left pointer to the right (since we need a larger value).
    • Otherwise, move the right pointer to the left.
  6. Repeat steps 3-5 until the pointers meet in the middle or cross each other.

The time complexity of this solution is O(N log N) due to the sorting step. The space complexity is O(1) as we only use a constant amount of extra space for storing our variables.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Arrays;

public class Solution {
    public static int race(int[] arr) {
        Arrays.sort(arr);
        int max_diff = arr[1] - arr[0];
        for (int i = 1; i < arr.length - 1; i++) {
            int diff = arr[i + 1] - arr[i];
            if (diff > max_diff) {
                max_diff = diff;
            }
        }
        return max_diff;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.