Maximum Product of Two Elements in an Array - Problem

Given an array of integers nums, your task is to find two different elements that will give you the maximum possible product when you subtract 1 from each and multiply them together.

More specifically, you need to choose two different indices i and j from the array and return the maximum value of (nums[i] - 1) * (nums[j] - 1).

Example: If you have the array [3, 4, 5, 2], you could pick indices 1 and 2 (values 4 and 5) to get (4-1) * (5-1) = 3 * 4 = 12, which happens to be the maximum possible product!

๐ŸŽฏ Goal: Find the pair of elements that maximizes the product after subtracting 1 from each.

Input & Output

example_1.py โ€” Basic Case
$ Input: [3,4,5,2]
โ€บ Output: 12
๐Ÿ’ก Note: We can choose indices 1 and 2 (values 4 and 5). The product is (4-1)*(5-1) = 3*4 = 12, which is the maximum possible.
example_2.py โ€” Larger Numbers
$ Input: [1,5,4,5]
โ€บ Output: 16
๐Ÿ’ก Note: We can choose indices 1 and 3 (both values are 5). The product is (5-1)*(5-1) = 4*4 = 16.
example_3.py โ€” Minimum Case
$ Input: [3,7]
โ€บ Output: 12
๐Ÿ’ก Note: With only two elements, we must choose both. The product is (3-1)*(7-1) = 2*6 = 12.

Constraints

  • 2 โ‰ค nums.length โ‰ค 500
  • 1 โ‰ค nums[i] โ‰ค 103
  • You must choose two different indices (i โ‰  j)

Visualization

Tap to expand
Maximum Product StrategyArray: [3, 4, 5, 2]34522nd Max1st MaxKey Insight:Since (a-1) ร— (b-1) where a,b > 1Maximum product = Two largest values!Calculation:Product = (5 - 1) ร— (4 - 1)= 4 ร— 3= 12Algorithm Options:Brute Force: O(nยฒ) - Check all pairsSorting: O(n log n) - Sort & pick last 2One Pass: O(n) - Track 2 maximums
Understanding the Visualization
1
Survey All Competitors
Look at each person's strength level in the array
2
Find the Champions
Identify the two strongest competitors
3
Calculate Prize Money
Multiply their adjusted strengths: (max-1) ร— (second_max-1)
Key Takeaway
๐ŸŽฏ Key Insight: Since we're multiplying positive numbers (after subtracting 1), the maximum product always comes from the two largest values in the array!
Asked in
Amazon 45 Microsoft 32 Apple 28 Google 15
67.2K Views
High Frequency
~12 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen