Maximum absolute difference in an array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The maximum absolute difference between two elements in an array is simpler than it first sounds. You do not need to compare every pair. The largest absolute difference is always the distance between the array's minimum value and maximum value.
Why the answer is max - min
For any two values a and b, the absolute difference is:
To make that as large as possible, choose the smallest and largest elements available. No other pair can produce a wider spread than the extremes of the array.
So the problem reduces to:
- find the minimum element
- find the maximum element
- subtract
Linear-time solution
That gives an O(n) algorithm with constant extra space.
The result here is 14, coming from 10 - (-4).
Why brute force is unnecessary
A naive solution checks every pair of elements:
That works, but it is O(n^2), which is unnecessary once you notice that only the minimum and maximum matter.
Edge cases
A few cases are worth handling explicitly:
- empty array: no valid answer
- one element: maximum absolute difference is
0 - duplicate values: still fine, because min and max may be equal
Example:
The formula still holds.
Built-in helpers are fine too
In Python, the shortest correct solution is:
This is still linear time because max and min each scan the array once.
If you are in an interview or a low-level language without convenient built-ins, the explicit one-pass loop is often better because it shows the underlying reasoning.
Returning the pair as well as the value
If you need not only the maximum difference but also the elements that produce it, return the minimum and maximum values alongside the difference. The same scan that finds the answer can also keep those two values without changing the overall time complexity.
Be careful about problem variants
Some problems sound similar but are different, such as:
- maximize
|A[i] - A[j]| + |i - j| - require
i < j - ask for the pair itself rather than only the value
For the plain maximum absolute difference in an array, max - min is enough. For the variants, the solution can change.
Common Pitfalls
- Using a nested-loop brute-force solution when only min and max matter.
- Forgetting to handle the empty-array case.
- Confusing this problem with harder indexed variants involving
iandj. - Returning
abs(max - min)even thoughmax - minis already non-negative. - Overcomplicating the solution when the array extremes already contain the answer.
Summary
- The maximum absolute difference in an array is always
max(arr) - min(arr). - You only need the minimum and maximum elements, not every pair.
- The optimal algorithm is linear time with constant extra space.
- Handle empty arrays explicitly and single-element arrays naturally return
0. - Watch out for similarly worded variants that add index terms or ordering constraints.

