Find the largest possible difference in an array with the smaller integer occurring earlier
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
This problem asks for the maximum value of arr[j] - arr[i] where index i is earlier than j. It is the same core pattern used in one-transaction stock-profit questions. A brute-force search works but scales poorly, so an O(n) scan is the practical solution.
Problem Restatement
Given an integer array, find the largest difference between two elements such that:
- The smaller value comes first in the array.
- The larger value comes later.
You can return only the numeric difference, or return both indices and values to explain the result.
Brute Force vs Linear Scan
Brute force checks every pair and computes all differences.
This is simple but time complexity is quadratic, which gets expensive quickly.
The optimal linear idea is:
- Keep the minimum value seen so far on the left.
- At each position, compute current value minus that minimum.
- Update global best difference when larger.
Optimal O(n) Algorithm
Complexity:
- Time is linear.
- Extra space is constant.
This is optimal for a single pass over a static array.
Edge Cases and Result Semantics
Your API should define behavior for decreasing arrays. Example array [9, 7, 4, 1] has maximum difference -2 if you require distinct indices and allow negative results.
Alternative semantics used in finance-style tasks clamp to zero when no profitable pair exists.
Pick one semantic and document it. Ambiguous expectations cause subtle bugs in downstream logic.
Streaming and Large Data
If values arrive as a stream, you can run the same logic online without storing all values.
This keeps memory constant and is suitable for telemetry pipelines or large log processing jobs.
Testing Strategy
Include tests for:
- Strictly increasing arrays.
- Strictly decreasing arrays.
- Repeated values.
- Negative numbers.
- Short arrays with zero or one element.
Common Pitfalls
- Checking all pairs in production code. Fix by tracking running minimum in one pass.
- Forgetting index order condition. Fix by only comparing current value against past minimum, never future values.
- Returning zero by default without defined semantics. Fix by documenting whether negative maximum is allowed.
- Mishandling short arrays. Fix by returning
Noneor raising clear error for fewer than two elements. - Tracking minimum value but not its index. Fix by keeping both value position and best pair indices.
Summary
- The optimal algorithm is a single left-to-right scan with a running minimum.
- Time complexity is linear and space complexity is constant.
- Decide early whether negative maximum differences are valid outputs.
- The same logic works for arrays and streaming inputs.
- Keep tests focused on boundary cases and semantic expectations.

