Maximum Product of Two Elements in an Array - Problem

Given an array of integers nums, you will choose two different indices i and j of that array.

Return the maximum value of (nums[i]-1) * (nums[j]-1).

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,5,2]
Output: 12
💡 Note: Choose indices 1 and 2: (4-1) * (5-1) = 3 * 4 = 12
Example 2 — Minimum Size
$ Input: nums = [1,5]
Output: 0
💡 Note: Only two elements: (1-1) * (5-1) = 0 * 4 = 0
Example 3 — All Same Values
$ Input: nums = [3,3,3,3]
Output: 4
💡 Note: All elements equal: (3-1) * (3-1) = 2 * 2 = 4

Constraints

  • 2 ≤ nums.length ≤ 500
  • 1 ≤ nums[i] ≤ 103

Visualization

Tap to expand
Maximum Product of Two Elements INPUT nums = [3, 4, 5, 2] i=0 i=1 i=2 i=3 3 4 5 2 Largest 2nd Largest Find two largest elements to maximize product (nums[i]-1) * (nums[j]-1) Formula to maximize ALGORITHM STEPS 1 Initialize Trackers max1 = 0, max2 = 0 2 Iterate Through Array Check each element once 3 Update Two Largest If num > max1: shift values Else if num > max2: update 4 Return Result (max1-1) * (max2-1) Tracking Progress: num=3: max1=3, max2=0 num=4: max1=4, max2=3 num=5: max1=5, max2=4 num=2: max1=5, max2=4 FINAL RESULT Two Largest Found: 5 max1 4 max2 Calculation: (5-1) * (4-1) = 4 * 3 Output: 12 [OK] Maximum Product O(n) time, O(1) space Key Insight: To maximize (nums[i]-1) * (nums[j]-1), we need the two largest values in the array. By tracking only max1 and max2 in one pass, we achieve O(n) time and O(1) space complexity. No need to sort the entire array -- just find the two maximum elements! TutorialsPoint - Maximum Product of Two Elements in an Array | One Pass - Track Two Largest
Asked in
Amazon 15 Microsoft 8
25.0K Views
Medium Frequency
~10 min Avg. Time
850 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