Skip to main content

Maximum Product of Three Elements After One Replacement - Solution & Explanation

MediumArrayMathGreedySorting9 min readAsked at: Meta, Google
Practice this problem

Problem Statement

You are given an integer array nums.

You must replace exactly one element in the array with any integer value in the range [-105, 105] (inclusive).

After performing this single replacement, determine the maximum possible product of any three elements at distinct indices from the modified array.

Return an integer denoting the maximum product achievable.

 

Example 1:

Input: nums = [-5,7,0]

Output: 3500000

Explanation:

Replacing 0 with -105 gives the array [-5, 7, -105], which has a product (-5) * 7 * (-105) = 3500000. The maximum product is 3500000.

Example 2:

Input: nums = [-4,-2,-1,-3]

Output: 1200000

Explanation:

Two ways to achieve the maximum product include:

  • [-4, -2, -3] → replace -2 with 105 → product = (-4) * 105 * (-3) = 1200000.
  • [-4, -1, -3] → replace -1 with 105 → product = (-4) * 105 * (-3) = 1200000.
The maximum product is 1200000.

Example 3:

Input: nums = [0,10,0]

Output: 0

Explanation:

There is no way to replace an element with another integer and not have a 0 in the array. Hence, the product of all three elements will always be 0, and the maximum product is 0.

 

Constraints:

  • 3 <= nums.length <= 105
  • -105 <= nums[i] <= 105

Approach Overview

Problem Overview: You are given an integer array and allowed to replace exactly one element with another value that maximizes the product of any three elements. The goal is to compute the largest possible product of three numbers after performing at most one optimal replacement.

The tricky part is that the maximum product of three numbers does not always come from the three largest values. Two large negative numbers multiplied with a large positive number can produce a larger result. Because of this, the solution focuses on extreme values in the array.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

The most direct method is to try every possible triplet of indices and compute their product. To simulate the replacement, you would also test variations where one of the elements in the triplet is replaced with another candidate value. This requires three nested loops to generate all triplets and additional checks for replacement scenarios. The method guarantees correctness but quickly becomes impractical for large arrays since the number of combinations grows as O(n^3). Space usage stays O(1) because only a few variables are needed to track the maximum product.

Approach 2: Greedy with Sorting (O(n log n) time, O(1) space)

A more practical approach relies on sorting. After sorting the array, the elements that can produce the maximum product must come from the extremes of the sorted list. Specifically, there are two important candidate combinations: the three largest numbers, or the largest number combined with the two smallest numbers (which may both be negative). Sorting places these candidates in predictable positions, allowing you to evaluate them in constant time.

When considering one replacement, the greedy insight is that the optimal modification will push one of the extreme values even further in the direction that benefits the product. That means the final optimal triplet will still be formed from numbers near the start or end of the sorted array. Instead of evaluating every replacement explicitly, compute the candidate products formed by these extreme values and track the maximum. This works because any optimal configuration must include either the largest values or the pair of most negative values.

The algorithm sorts the array, evaluates the candidate products using values at the edges, and returns the largest result. Sorting costs O(n log n), while the product checks run in constant time. Space usage remains O(1) if sorting is done in place.

Conceptually, this is a greedy observation layered on top of array manipulation: the optimal product always emerges from extreme values, not the middle of the list. The math behind negative multiplication explains why the smallest numbers must also be considered, connecting the logic to basic math properties.

Recommended for interviews: Interviewers typically expect the sorting-based greedy solution. A brute force explanation shows you understand the search space, but recognizing that only extreme values matter demonstrates algorithmic insight. The O(n log n) sorting approach is concise, easy to implement, and reliably handles negative numbers and edge cases.

Solution

According to the problem description, we can replace one element in the array with any integer in the range [-10^5, 10^5]. To maximize the product of three elements, we can consider the following cases:

  1. Select the two smallest elements in the array and replace the third element with 10^5.
  2. Select the two largest elements in the array and replace the third element with 10^5.
  3. Select the smallest element and the two largest elements in the array, and replace the middle element with -10^5.

The maximum product among these three cases is the answer.

Therefore, we can first sort the array, then calculate the products for the above three cases, and return the maximum value among them.

The time complexity is O(n log n) and the space complexity is O(log n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force TripletsO(n^3)O(1)Educational baseline or very small arrays
Greedy with SortingO(n log n)O(1)General case; easiest reliable approach using extreme values
Single Pass Tracking ExtremesO(n)O(1)When sorting is unnecessary and only top/bottom values are tracked

Video Solution

Leetcode Weekly Contest 474 Q2. Maximum Product of Three Elements After One Replacement #python #dsa • ADevOpsEngineer • 384 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Maximum Product of Three Elements After One Replacement easy or hard?
The problem is typically classified as Medium. The main challenge is recognizing that the maximum product may involve negative numbers, so both the largest values and the smallest values must be considered. Once that insight is clear, the implementation is straightforward.
Maximum Product of Three Elements After One Replacement Python/Java solution
Most implementations follow the same pattern: sort the array, compute the product of the three largest values, compute the product of the largest value with the two smallest values, and return the maximum. This logic translates directly to Python, Java, C++, Go, and TypeScript with only minor syntax differences.
How to solve Maximum Product of Three Elements After One Replacement in O(n)?
An O(n) approach tracks the three largest values and the two smallest values during a single pass through the array. Using these extremes, compute the candidate products that could produce the maximum result. This avoids sorting while still capturing the combinations that matter for the final answer.
What is the best approach for Maximum Product of Three Elements After One Replacement?
The most practical solution uses sorting and a greedy observation. After sorting the array, the maximum product must come from either the three largest numbers or the largest number combined with the two smallest numbers. Evaluating these candidate combinations after one optimal replacement gives the maximum result in O(n log n) time and O(1) extra space.
Is Maximum Product of Three Elements After One Replacement asked at Google/Amazon/Meta?
Variants of maximum product problems frequently appear in interviews at companies like Amazon, Meta, and Google. They test understanding of array manipulation, negative number behavior, and greedy reasoning about extreme values rather than brute force enumeration.
What data structure is used in Maximum Product of Three Elements After One Replacement?
The solution mainly relies on arrays and simple value tracking. In the sorting approach, the array is sorted to easily access the smallest and largest elements. In the optimized linear approach, a few variables track the top three maximum values and the two minimum values.
What is the time complexity of Maximum Product of Three Elements After One Replacement?
The common interview solution sorts the array, giving O(n log n) time complexity. After sorting, computing candidate products takes constant time. Space complexity is O(1) if the array is sorted in place.

Ready to solve this problem?

Practice Maximum Product of Three Elements After One Replacement with our built-in code editor and test cases.

Practice on FleetCode