algorithm
mathematics
problem-solving
programming
coding

Finding highest product of three numbers

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In computer science and mathematics, finding the highest product of three numbers in an array or list is a common problem. It challenges both the understanding of algorithms and the application of mathematical properties. In this article, we delve into the intricacies of finding the highest product efficiently, present algorithmic approaches, and cover edge cases thoroughly.

Problem Description

Given a set of integers, the task is to find the maximum product achieved by multiplying any three of those integers. This problem is not only about brute calculation but requires insights into number properties such as negatives and positives interactions.

Mathematical Foundation

At a high level, the product of three numbers, aa, bb, and cc is represented as:

P(a,b,c)=a×b×cP(a, b, c) = a \times b \times c

The simplicity of multiplication cloaks the complexity that arises when dealing with both negative and positive numbers within the list. The primary rule here is:

  • The product is maximized by multiplying the largest numbers available, irrespective of their sign.

Key Observations

  1. Positives Only: With all positive numbers, the product is straightforwardly maximized by the three largest numbers.
  2. Inclusion of Negatives: Introducing negative numbers adds complexity. A product of two negatives yields a positive, potentially resulting in a higher product when combined with a large positive number.
  3. Zero as a Factor: Multiplying by zero results in zero, hence zero is neutral in this optimization context but may serve other purposes like negating negative outcomes.

Algorithmic Approach

A naive solution involves checking every triplet combination, which is computationally burdensome with time complexity O(n3)O(n^3). Advanced methods reduce this by integrating clever logic.

Efficient Solution

The optimized approach reduces time complexity to O(n)O(n) for a single pass solution:

  1. Initialization: Track the top three largest numbers and the two smallest numbers (to handle negative cases).
  2. Single Pass Calculation: Traverse the list to update these top and bottom trackers.
  3. Determination: Finally, compute two potential products:
    • Product of the top three numbers.
    • Product of the two smallest numbers (both negative) with the largest number.
  4. Output: The maximum of these two products.

Pseudocode


Course illustration
Course illustration

All Rights Reserved.