Skip to main content

Case Study: Maximum Pairwise Product

20 min readRead first: Algorithmic Thinking

To truly understand why algorithmics matters, it helps to experience failure first. In this case study we take a deceptively simple problem and solve it again and again. Each version fixes a problem of the previous one, and each fix teaches a different lesson: about the limits of data types, the cost of naive strategies, the impact of data representation, and the danger of "optimizations" that are not actually correct.

This is exactly the attitude described in the previous lesson: a good algorithm designer refuses to be content with the first solution that works.

What you will learn in this lesson
  • How to state a problem precisely and check your understanding with small examples.
  • Why arithmetic overflow happens, why it is silent in Java, and how to avoid it correctly.
  • How the number of operations of a brute-force solution grows, and why faster hardware does not fix it.
  • How sorting and, finally, a single linear scan reduce the cost from quadratic to linear time.
  • How data representation affects memory consumption.
  • How to gain confidence in a fast algorithm using stress testing, and how a plausible-looking optimization can be wrong.

The Problem Statement​

Objective: given a sequence of non-negative integers, find the maximum product that can be obtained by multiplying two elements located at different positions of the sequence.

Formal specification:

  • Input: a sequence A=[a0,a1,…,an−1]A = [a_0, a_1, \dots, a_{n-1}] of non-negative integers, with n≥2n \ge 2.
  • Output: the value max⁡{ ai⋅aj:0≤i,j≤n−1,  i≠j }\max \{\, a_i \cdot a_j : 0 \le i, j \le n-1,\; i \ne j \,\}.

Before writing any code, it is good practice to solve a few small instances by hand. This checks that we understand the problem and gives us test cases for later:

  • For [7, 3, 6] the possible products are 7⋅3=217 \cdot 3 = 21, 7⋅6=427 \cdot 6 = 42 and 3⋅6=183 \cdot 6 = 18, so the answer is 42.
  • For [5, 5] the answer is 25. The two factors may have the same value, as long as they are at different positions. This detail, which is easy to overlook, will matter later.
  • For [0, 9] the answer is 0: with only two elements there is only one possible pair.
Read the specification carefully

"Two distinct elements" is ambiguous in everyday language: distinct values or distinct positions? The formal specification (i≠ji \ne j) removes the ambiguity. Many bugs come from implementing the problem we think we read instead of the one that was actually specified.


Step 1: Two Numbers and the Primitive Type Trap​

Let us start with the simplest possible instance: just two numbers, 100,000 and 1,000,000. The expected result is 1011=100,000,000,00010^{11} = 100{,}000{,}000{,}000.

public class MaxPairWiseProduct {
private final int operandA = 100_000;
private final int operandB = 1_000_000;

public int compute() {
return operandA * operandB;
}
}

If we run it, the program prints 1215752192. No exception, no warning: just a wrong number.

Arithmetic overflow

The Java type int uses 32 bits and can represent values in the range [−231,231−1][-2^{31}, 2^{31}-1], that is, up to 2,147,483,6472{,}147{,}483{,}647. When the true result of an operation does not fit, Java keeps only the lowest 32 bits of the result. Mathematically, the value is reduced modulo 2322^{32} and interpreted in two's complement:

1011 mod 232=1,215,752,19210^{11} \bmod 2^{32} = 1{,}215{,}752{,}192

The result is not random: it is completely deterministic. But it is wrong, and nothing tells us so. Depending on the operands, the "wrapped" value can even be negative.

The size of the primitive types is part of the language specification (unlike in C or C++, where it may depend on the platform):

TypeSizeRange
byte8 bits−128-128 to 127127
short16 bits−32,768-32{,}768 to 32,76732{,}767
int32 bitsabout ±2.1×109\pm 2.1 \times 10^{9}
long64 bitsabout ±9.2×1018\pm 9.2 \times 10^{18}

Step 2: Moving to long, and a Second Trap​

The obvious fix is to use 64-bit integers, which can store values up to about 9.22×10189.22 \times 10^{18}:

private final long operandA = 100_000L;
private final long operandB = 1_000_000L;

public long compute() {
return operandA * operandB; // 100000000000, correct
}

This works. However, in real programs the inputs usually arrive as int values (for example, read from a file or stored in an int[]), and a very common mistake is to change only the type of the variable that stores the result:

int a = 100_000, b = 1_000_000;
long wrong = a * b; // 1215752192: the multiplication is still done in 32 bits!
long right = (long) a * b; // 100000000000: a is promoted to long BEFORE multiplying

In a * b, both operands are int, so Java performs a 32-bit multiplication, overflows, and only then converts the already wrong result to long. Casting one of the operands forces a 64-bit multiplication.

Is long always enough?

For this problem, yes. If the inputs are int values, each one is at most 231−12^{31}-1, so any product is at most (231−1)2≈4.6×1018(2^{31}-1)^2 \approx 4.6 \times 10^{18}, which is below the maximum long value (263−1≈9.22×10182^{63}-1 \approx 9.22 \times 10^{18}). This is a small example of reasoning about the whole input domain instead of trusting a few tests.

When you cannot bound the values like this, use Math.multiplyExact(a, b), which throws an ArithmeticException instead of overflowing silently, or java.math.BigInteger for arbitrary precision.

Lesson 1: always respect the physical limits of your data types, and remember that in most languages overflow is silent.


Step 3: A Realistic Input​

Two numbers are not an interesting instance. Let us create a realistic dataset: 100,000 random integers between 0 and 99, written to a text file so that every version of our algorithm works with exactly the same data.

public static void main(String... args) throws IOException {
Path path = Paths.get("MaxPairWiseProductRandomNumbers.txt");
Random random = new Random();
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
for (int i = 0; i < 100_000; i++) {
writer.write(random.nextInt(100) + " ");
}
}
}

Each version then reads the file into a list in its constructor:

private final List<Integer> numbers = new ArrayList<>();

public MaxPairWiseProduct3() {
Path path = Paths.get("MaxPairWiseProductRandomNumbers.txt");
try (BufferedReader reader = Files.newBufferedReader(path)) {
for (String number : reader.readLine().split(" ")) {
numbers.add(Integer.valueOf(number));
}
} catch (IOException e) {
// log the error
}
}
🧠 Checkpoint: Predict the answer

Question: Before running any algorithm, what result do you expect for this dataset?

Answer: Almost certainly 99⋅99=980199 \cdot 99 = 9801. With 100,000 values uniformly distributed between 0 and 99, the value 99 is expected to appear about 1,000 times, so it is practically certain that it appears at least twice, at two different positions. Predicting the result is a cheap and useful sanity check for any program.


Step 4: The Brute-Force Approach​

The most direct strategy follows the specification literally: try every pair of positions (i,j)(i, j) with i≠ji \ne j, compute the product and keep the largest.

public long compute() {
long maxProduct = 0;
for (int i = 0; i < numbers.size(); i++) {
for (int j = 0; j < numbers.size(); j++) {
if (i != j) {
long result = (long) numbers.get(i) * numbers.get(j);
if (result > maxProduct) {
maxProduct = result;
}
}
}
}
return maxProduct;
}

This algorithm is correct: it examines all candidate pairs, so it cannot miss the best one. Its problem is cost.

Counting the work​

The inner body is executed n⋅n=n2n \cdot n = n^2 times (and the product is computed n(n−1)n(n-1) times). For n=100,000n = 100{,}000 that is 101010^{10} iterations: ten thousand million.

A first improvement is to notice that ai⋅aj=aj⋅aia_i \cdot a_j = a_j \cdot a_i, so each pair only needs to be checked once. Starting the inner loop at j = i + 1 also makes the i != j test unnecessary:

for (int i = 0; i < numbers.size(); i++)
for (int j = i + 1; j < numbers.size(); j++)
...

Now the body runs n(n−1)2\frac{n(n-1)}{2} times, about 5×1095 \times 10^9 for our dataset. We have halved the work, which is welcome, but the shape of the growth has not changed: it is still proportional to n2n^2.

What happens in practice​

The following times were measured on one machine, with an int[] version of these algorithms and the JIT compiler enabled. The exact numbers will be different on your computer; what matters is how they grow:

nnAll pairs (n2n^2)Half of the pairs (n2/2n^2/2)
10,0000.08 s0.06 s
20,0000.22 s0.07 s
40,0000.89 s0.29 s
100,0005.8 s1.8 s

Look at the left column: when nn doubles from 20,000 to 40,000, the time is multiplied by about 4. When nn grows 2.5 times (from 40,000 to 100,000), the time grows about 2.52≈6.252.5^2 \approx 6.25 times. This is the signature of quadratic growth. Extrapolating, one million numbers would take around ten minutes, and ten million numbers around 16 hours.

The limits of hardware

A quadratic algorithm cannot be rescued by buying a faster processor. A machine that is twice as fast lets you process, in the same time, an input only 2≈1.41\sqrt{2} \approx 1.41 times larger. Doubling the input still quadruples the time, whatever the hardware.

🧠 Checkpoint: Faster CPU or better algorithm?

Question: Your quadratic program takes one hour for a certain input. You can either buy a CPU that is 4 times faster, or replace the algorithm with one whose time grows linearly. Which option lets you process a 100 times larger input in about one hour?

Answer: Only the better algorithm. With the faster CPU, a 100 times larger input needs 1002=10,000100^2 = 10{,}000 times more work, which takes 10,000/4=2,50010{,}000 / 4 = 2{,}500 hours. A linear algorithm only needs 100 times more work than it needed for the original input, and for large inputs a linear algorithm is usually far faster than the quadratic one to begin with.

Lesson 2: a correct algorithm can still be useless if its cost grows too fast. We need a better strategy, not a faster machine.


Step 5: Improving Time by Sorting​

Brute force wastes most of its time multiplying small numbers that can never produce the maximum. The key observation is:

Since all numbers are non-negative, the maximum product is always obtained by multiplying the two largest elements.

(If x≥yx \ge y are the two largest values, any other pair ai⋅aja_i \cdot a_j satisfies ai≤xa_i \le x and aj≤ya_j \le y for a suitable ordering of the pair, so ai⋅aj≤x⋅ya_i \cdot a_j \le x \cdot y.)

A natural way of finding the two largest elements is to sort the data. Sorting in descending order places them in the first two positions:

public long compute() {
if (numbers.size() < 2)
throw new IllegalStateException("At least two numbers are required");

numbers.sort(Collections.reverseOrder()); // largest first
long candidate1 = numbers.get(0);
long candidate2 = numbers.get(1);
return candidate1 * candidate2;
}

(An equivalent formulation is to sort in ascending order with Collections.sort and then reverse the list with Collections.reverse.)

Good sorting algorithms need a number of operations proportional to nlog⁡2nn \log_2 n, as you will see in the sorting chapter. For n=100,000n = 100{,}000 that is about 1.7×1061.7 \times 10^6 basic steps instead of 5×1095 \times 10^9. In our measurements, the time drops from seconds to a few milliseconds: more than a thousand times faster than the all-pairs brute force.

A side effect

This version modifies the caller's data: after calling compute(), the list is sorted. If other parts of the program relied on the original order, we have introduced a bug that has nothing to do with the maximum product. When an algorithm needs to reorder its input, it should either document it clearly or work on a copy (which costs extra memory).


Step 6: Removing Unnecessary Work​

Do we need the descending order (or the extra pass to reverse the list)? No. After an ascending sort, the two largest elements are simply at the end:

public long compute() {
if (numbers.size() < 2)
throw new IllegalStateException("At least two numbers are required");

Collections.sort(numbers); // ascending
long candidate1 = numbers.get(numbers.size() - 1);
long candidate2 = numbers.get(numbers.size() - 2);
return candidate1 * candidate2;
}

Asymptotically, nothing has changed: the cost is still dominated by the sort, proportional to nlog⁡nn \log n. But we have removed work that was not needed (a custom comparator or a full reversal of the list). This illustrates a distinction that we will formalise in the next lessons:

  • improvements that change the growth rate of the cost (from n2n^2 to nlog⁡nn \log n), which are decisive for large inputs, and
  • improvements that only change the constant factors (doing the same kind of work, but less of it), which are useful but secondary.

Step 7: The Optimal Linear Solution​

Sorting rearranges all the elements, but we only need two of them. Can we find the two largest elements without sorting? Yes, with a single pass over the data, keeping track of the largest and the second largest values seen so far:

public long compute() {
if (numbers.size() < 2)
throw new IllegalStateException("At least two numbers are required");

long max1 = -1; // largest value seen so far
long max2 = -1; // second largest value seen so far

for (int current : numbers) {
if (current > max1) {
max2 = max1; // the previous maximum becomes the second
max1 = current; // new maximum
} else if (current > max2) {
max2 = current; // not the largest, but beats the second
}
}
return max1 * max2;
}

Let us trace it with [5, 3, 5]:

ElementComparisonmax1max2
(start)—-1-1
55>−15 > -1: new maximum5-1
33≤53 \le 5, 3>−13 > -1: new second53
55≤55 \le 5, 5>35 > 3: new second55

The result is 5⋅5=255 \cdot 5 = 25, which is correct: the two 5s are at different positions. Note that the second 5 goes to max2 precisely because the first comparison uses a strict >.

This algorithm:

  • reads each element exactly once, so its time is proportional to nn (linear);
  • uses only two extra variables, whatever the size of the input (constant extra memory);
  • does not modify the input.

In our measurements, it processes the 100,000 numbers in about a tenth of a millisecond, roughly 30 times faster than sorting and tens of thousands of times faster than brute force. And it is optimal in an important sense: any correct algorithm must read every element at least once (an unread element could be the largest), so no algorithm can grow more slowly than linearly.

ProofThe linear maximum pairwise product is correct

Reducing Memory Consumption​

So far we have focused on time, but an efficient solution must also take care of memory consumption. There are two sources of memory use to consider.

1. Auxiliary memory of the algorithm. Brute force and the linear scan need only a few variables. Sorting a list of objects in Java, on the other hand, uses an algorithm (TimSort) that may need temporary space for up to about n/2n/2 elements, that is, memory proportional to nn. (Sorting an int[] with Arrays.sort uses a variant of Quicksort that works almost in place.) If we sort a copy to avoid the side effect described in Step 5, we need yet another nn elements.

2. Representation of the data. All the versions store the numbers in a List<Integer>. In Java, a list cannot hold primitive values, so each number is stored as an Integer object: a reference in the list plus an object in the heap (typically around 16 bytes) for each element. An int[] stores each number in exactly 4 bytes, contiguously in memory, which is also friendlier to the processor cache.

int[] numbers = new int[100_000]; // about 400 KB of data
A curiosity: the Integer cache

Java keeps a cache of Integer objects for small values (by default, from −128-128 to 127127). Since our numbers are between 0 and 99, Integer.valueOf always returns cached objects, and the list stores only references. With larger values, every element would be a separate object, and the list would need several times more memory than an int[]. Measuring memory in a managed language is full of subtleties like this one.

StrategyGrowth of the timeExtra memoryModifies the inputTime for n=105n = 10^5 (measured)
Brute force, all pairsn2n^2constantno≈ 5.8 s
Brute force, half of the pairsn2n^2constantno≈ 1.8 s
Sortingnlog⁡nn \log nproportional to nnyes (unless copied)≈ 3.6 ms
Linear scannnconstantno≈ 0.1 ms

Lesson 3: efficiency is about all the resources. The best solution here wins in time, in memory and in side effects.


Is the Fast Version Really Correct? Stress Testing​

Fast algorithms are usually more subtle than slow ones, and subtle code hides subtle bugs. Consider this version, which looks perfectly reasonable: first find the maximum, then find the largest value that is different from it.

public static long buggyMaxPairwise(int[] a) {
int max1 = -1;
for (int x : a) if (x > max1) max1 = x;

int max2 = -1;
for (int x : a) if (x != max1 && x > max2) max2 = x; // BUG

return (long) max1 * max2;
}

It passes the obvious tests: [7, 3, 6] gives 42, [1, 2, 3, 4] gives 12. But it excludes the maximum by value, not by position. For [5, 5] it computes 5⋅(−1)=−55 \cdot (-1) = -5 instead of 25, and on our dataset (where 99 appears about 1,000 times) it would return 99⋅98=970299 \cdot 98 = 9702 instead of 9801.

How can we find such bugs systematically? A powerful technique is stress testing:

  1. Keep a simple, obviously correct (even if slow) implementation: the brute force.
  2. Generate thousands of small random inputs.
  3. Run both implementations on each input and compare the results.
  4. As soon as they differ, print the input: it is a counterexample that you can debug by hand.
Random random = new Random();
for (int test = 0; test < 100_000; test++) {
int n = 2 + random.nextInt(8); // small sizes: 2..9
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = random.nextInt(10); // small values: 0..9

long expected = bruteForce(a);
long actual = buggyMaxPairwise(a);
if (expected != actual) {
System.out.println("Counterexample: " + Arrays.toString(a)
+ " expected " + expected + " but got " + actual);
break;
}
}

When we ran it (with a fixed random seed), it found a counterexample in the very first test: [3, 8, 4, 0, 5, 5, 8], where the correct answer is 8⋅8=648 \cdot 8 = 64 but the buggy version returns 8⋅5=408 \cdot 5 = 40. The same stress test, applied to the sorting and linear versions, found no differences in 100,000 random tests.

Why small inputs?

Random small inputs with small values are best: repeated values (like the two 8s above) appear frequently, and when a test fails, the counterexample is short enough to analyze by hand. Then complement random tests with deliberate edge cases: the minimum size (n=2n = 2), all elements equal, zeros, the maximum allowed values (to detect overflow) and the largest input sizes (to detect performance problems).

Remember that testing, even stress testing, can show the presence of bugs but not their absence. For the linear scan we also have an argument: after processing each element, max1 and max2 hold the two largest values (counting repetitions) among the elements processed so far. This statement, which remains true after every iteration, is a loop invariant, a tool that you will meet again when reasoning about the correctness of algorithms.

Lesson 4: an optimization is only an improvement if it is still correct. Keep the slow version: it is your best oracle.


Going Further: What If Negative Numbers Are Allowed?​

Our specification said non-negative integers. Let us change it: the input may now contain negative numbers. Is the product of the two largest values still the answer?

🧠 Checkpoint: Negative numbers

Question: What is the maximum pairwise product of [-10, -9, 1, 3]? Does the linear algorithm still work?

Answer: The answer is (−10)⋅(−9)=90(-10) \cdot (-9) = 90, not 1⋅3=31 \cdot 3 = 3: the product of two negative numbers is positive. With negative numbers allowed, the maximum product is either the product of the two largest values or the product of the two smallest values (the two most negative ones). The algorithm can be adapted by keeping track of four values in the same single pass (the two largest and the two smallest) and returning the larger of the two candidate products. It remains linear in time and constant in memory, but the initial values -1 no longer work as "nothing seen yet" and must be replaced (for example, by the first two elements).

Note how a small change in the specification invalidates a key step of the reasoning. Correctness is always relative to a specification.

Common mistakes
  • Storing an int product in a long and thinking it is safe. long r = a * b overflows before the assignment. Promote an operand first: (long) a * b.
  • Testing only with tiny inputs. Small examples hide overflows and slow algorithms. Test with realistic sizes.
  • Sorting the input inside the method. It solves the problem but modifies the caller's array: a side effect nobody asked for.
  • Trusting an optimization without checking it. Compare the fast version against a slow one you trust (stress testing).

Summary​

StepProblem detectedLesson
1. Two int numbersSilent arithmetic overflow.Respect the limits of data types.
2. Using longlong r = a * b still overflows with int operands.Promote operands before operating.
3. Realistic inputToy examples hide problems.Test with realistic sizes and predict the result.
4. Brute forceCorrect, but its cost grows quadratically.Hardware cannot fix a bad growth rate.
5. Sort descendingMuch faster, but modifies the input.Change the strategy; watch out for side effects.
6. Sort ascendingSame growth, less work.Distinguish growth rate from constant factors.
7. Linear scanOptimal in time and memory.Find exactly what you need, nothing more.
Stress testingPlausible "optimizations" can be wrong.Compare fast versions against a trusted slow one.

The rest of this chapter gives us the tools to make these intuitions precise: how to measure and count the cost of an algorithm, and how to describe its growth with asymptotic notation.


Practice​

  • 💻 Run the course versions. The course repository contains every version of this lesson in src/topics/foundation/maxpairwise: MaxPairWiseProduct (step 1) to MaxPairWiseProduct6 (step 7), the dataset generator MaxPairWiseProductRandomNumbers and a test class for each version. Run the tests and compare the times they report.
  • ⏱️ Reproduce the growth. Generate datasets of 10,000, 20,000, 40,000 and 80,000 numbers and measure the brute-force version. Does the time multiply by about 4 each time nn doubles? You will learn how to take reliable measurements in the first lab sessions.
  • 🐞 Break it and catch it. Implement buggyMaxPairwise and the stress test above. Then introduce other bugs in the linear version (for example, replace > with >=, or remove the else) and check whether the stress test detects them. Which ones survive? Why?
  • ➖ Allow negative numbers. Implement the linear version for integers of any sign, as described in the last checkpoint, and validate it with a stress test against brute force using values between −9-9 and 99.
  • 🔢 Generalize. Design an algorithm for the maximum product of three elements at different positions. How many candidates must you consider when negative numbers are allowed?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.