Problem Description
Given an integer array nums, choose two different indices i and j such that the product (nums[i]-1) * (nums[j]-1) is maximized. Return this maximum product.
Key Insights
- Only the two largest numbers in the array are needed to compute the maximum product.
- Sorting or a single pass can be used to identify the top two maximum elements.
- The formula subtracts 1 from each selected number, so even if the array has duplicates, the two largest values provide the answer.
Space and Time Complexity
Time Complexity: O(n) – scanning the array one time to find the two largest elements.
Space Complexity: O(1) – only constant extra space is used.
Solution
The solution involves iterating through the array once while keeping track of the two largest numbers encountered. After identifying these two numbers, we calculate the result using (max1-1) * (max2-1). This approach avoids the overhead of sorting and directly provides the answer in linear time. Edge cases such as small-sized input arrays are handled by the problem constraints ensuring there are always at least two elements.