Maximum Product of Three Elements After One Replacement Problem
Description
LeetCode Problem 3732.
You are given an integer array nums.
You must replace exactly one element in the array with any integer value in the range [-10^5, 10^5] (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 -10^5 gives the array [-5, 7, -10^5], which has a product (-5) * 7 * (-10^5) = 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 10^5 → product = (-4) * 10^5 * (-3) = 1200000.
- [-4, -1, -3] → replace -1 with 10^5 → product = (-4) * 10^5 * (-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 <= 10^5-10^5 <= nums[i] <= 10^5
Solution
Approach: Sorting
The replacement value is free, so it should be an extreme: 10^5 or -10^5. The best product then comes from one of three shapes, where the replaced element is the third factor:
- The two smallest numbers (two negatives give a positive) times
10^5. - The two largest numbers times
10^5. - The smallest and the largest number times
-10^5.
Sort the array, evaluate these three products using the two smallest and two largest elements, and return the maximum.
Complexity: time O(n log n), space O(1) extra (besides the sort). Products reach 10^15, so use 64-bit integers.
class Solution:
def maxProduct(self, nums: List[int]) -> int:
nums.sort()
a, b = nums[0], nums[1]
c, d = nums[-2], nums[-1]
x = 10**5
return max(a * b * x, c * d * x, a * d * -x)