array
algorithms
data structures
coding tutorial
programming tips

How to find the Largest Difference in an Array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The phrase "largest difference in an array" often means finding the maximum value of arr[j] - arr[i] where j > i. That order condition matters because the task is usually about a later value minus an earlier value, not simply max(array) - min(array).

Clarify The Problem First

There are two common versions of this problem.

  • ordered version: the larger element must appear after the smaller one
  • unordered version: any two elements are allowed, so the answer is just max(array) - min(array)

Most interview-style questions mean the ordered version, which is the same idea as maximum single-transaction stock profit.

Brute Force Solution

The direct approach is to check every valid pair.

python
1def largest_difference_bruteforce(nums):
2    if len(nums) < 2:
3        raise ValueError("need at least two numbers")
4
5    best = nums[1] - nums[0]
6    for i in range(len(nums)):
7        for j in range(i + 1, len(nums)):
8            best = max(best, nums[j] - nums[i])
9    return best
10
11print(largest_difference_bruteforce([2, 3, 10, 6, 4, 8, 1]))

This works, but it takes O(n^2) time because it considers every pair.

Linear-Time Solution

A better solution scans the array once, keeping track of the smallest value seen so far and the best difference found so far.

python
1def largest_difference(nums):
2    if len(nums) < 2:
3        raise ValueError("need at least two numbers")
4
5    min_so_far = nums[0]
6    best = nums[1] - nums[0]
7
8    for value in nums[1:]:
9        best = max(best, value - min_so_far)
10        min_so_far = min(min_so_far, value)
11
12    return best
13
14print(largest_difference([2, 3, 10, 6, 4, 8, 1]))

The idea is simple: at each position, ask what profit or difference would be achieved if you paired the current value with the smallest earlier value.

Walk Through An Example

For the array [2, 3, 10, 6, 4, 8, 1]:

  • start with min_so_far = 2
  • at 3, difference is 1
  • at 10, difference is 8, which becomes the current best
  • later values do not beat 8

So the answer is 8, from 10 - 2.

What If The Array Is Decreasing

The algorithm still works even if every later value is smaller. For [9, 7, 4, 1], the best ordered difference is negative because every valid pair loses value.

python
print(largest_difference([9, 7, 4, 1]))

That behavior is often correct. If the problem statement instead wants 0 when no positive gain exists, clamp the result with max(best, 0).

Space And Time Complexity

The optimized algorithm takes:

  • time: O(n)
  • extra space: O(1)

That is optimal for a single left-to-right scan.

If order does not matter, the answer is much simpler.

python
def largest_gap_any_order(nums):
    return max(nums) - min(nums)

This is a different problem, so it is worth checking the requirement before implementing the algorithm.

Common Pitfalls

A common mistake is returning max(nums) - min(nums) for the ordered version. That can be wrong if the minimum occurs after the maximum.

Another mistake is initializing the best value to 0, which hides valid negative answers for strictly decreasing arrays.

It is also easy to forget edge cases such as empty arrays or single-element arrays. Those inputs do not contain a valid pair, so the function should raise an error or return a documented sentinel value.

Summary

  • The ordered version asks for the maximum arr[j] - arr[i] with j > i.
  • A one-pass scan with min_so_far solves it in O(n) time.
  • Do not confuse the ordered version with simple max - min.
  • Decide whether negative answers are allowed or should be clamped to 0.
  • Handle arrays with fewer than two elements explicitly.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.