Maximum Product of Two Elements in an Array - Complete Solution Guide
Maximum Product of Two Elements in an Array is LeetCode problem 1464, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in java.
Problem Statement
Given the 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) . Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. Example 2: Input: nums = [1,5,4,5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of
Detailed Explanation
The problem asks you to find the maximum product that can be obtained by multiplying two distinct elements from an array, after subtracting 1 from each element. The input is an array of integers (`nums`), and the output is a single integer representing the maximum product. The constraints specify that the array will always have at least two elements, and the elements themselves will be positive integers within a specific range.
Solution Approach
The provided Java solution utilizes a simple and efficient approach. It first sorts the input array `nums` in ascending order. Then, it directly accesses the two largest elements (located at indices `nums.length - 1` and `nums.length - 2`) and calculates their product after subtracting 1 from each. This product is then returned as the maximum product.
Step-by-Step Algorithm
- Step 1: Sort the input array `nums` using `Arrays.sort(nums)`. This arranges the elements in ascending order.
- Step 2: Access the second-to-last element (`nums[nums.length - 2]`) and the last element (`nums[nums.length - 1]`).
- Step 3: Subtract 1 from each of these elements.
- Step 4: Multiply the results from Step 3 together.
- Step 5: Return the product calculated in Step 4.
Key Insights
- Insight 1: The maximum product will always be obtained by multiplying the two largest numbers in the array (after subtracting 1 from each).
- Insight 2: Sorting the array allows us to efficiently find the two largest elements.
- Insight 3: No special handling is needed for negative numbers because all numbers are positive; this simplifies the problem significantly.
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(1)
Topics
This problem involves: Array, Sorting, Heap (Priority Queue).
Companies
Asked at: Cisco, J.P. Morgan, Samsung.