703907. Maximum weight difference

Easy

Here is a detailed Markdown blog post for the "Maximum weight difference" problem:

Maximum Weight Difference

Summary

The problem involves finding the maximum absolute difference between weights in an array. The key concepts involved are arrays and data structures, specifically searching and sorting algorithms.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates through the array once. We keep track of the minimum and maximum weight encountered so far. For each element in the array, we update these values as needed to ensure that maxWeight - minWeight always represents the maximum absolute difference between weights.

Here is the step-by-step breakdown:

  1. Initialize two variables: minWeight to store the smallest weight and maxWeight to store the largest weight.
  2. Iterate through the array:
    • For each element, update minWeight if the current element is smaller than the previous minimum.
    • Update maxWeight if the current element is larger than the previous maximum.
  3. Return maxWeight - minWeight as the result.

Time complexity: O(n), where n is the length of the array. We only need to iterate through the array once, so the time complexity is linear.

Space complexity: O(1). We only use a constant amount of space to store the minimum and maximum weights, regardless of the size of the input array.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxWeightDifference(int[] weights) {
    int minWeight = Integer.MAX_VALUE;
    int maxWeight = Integer.MIN_VALUE;

    for (int weight : weights) {
        if (weight < minWeight) {
            minWeight = weight;
        } else if (weight > maxWeight) {
            maxWeight = weight;
        }
    }

    return Math.abs(maxWeight - minWeight);
}

DevExCode

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

© 2026 DevExCode. All rights reserved.