1464. Maximum Product of Two Elements in an Array LeetCode Solution
In this guide, you will get 1464. Maximum Product of Two Elements in an Array LeetCode Solution with the best time and space complexity. The solution to Maximum Product of Two Elements in an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Product of Two Elements in an Array solution in C++
- Maximum Product of Two Elements in an Array solution in Java
- Maximum Product of Two Elements in an Array solution in Python
- Additional Resources
Problem Statement of Maximum Product of Two Elements in an Array
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 (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1464. Maximum Product of Two Elements in an Array LeetCode Solution in C++
class Solution {
public:
int maxProduct(vector<int>& nums) {
int max1 = 0;
int max2 = 0;
for (const int num : nums)
if (num > max1)
max2 = std::exchange(max1, num);
else if (num > max2)
max2 = num;
return (max1 - 1) * (max2 - 1);
}
};
/* code provided by PROGIEZ */
1464. Maximum Product of Two Elements in an Array LeetCode Solution in Java
class Solution {
public int maxProduct(int[] nums) {
int max1 = 0;
int max2 = 0;
for (final int num : nums)
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
return (max1 - 1) * (max2 - 1);
}
}
// code provided by PROGIEZ
1464. Maximum Product of Two Elements in an Array LeetCode Solution in Python
class Solution:
def maxProduct(self, nums: list[int]) -> int:
max1 = 0
max2 = 0
for num in nums:
if num > max1:
max2, max1 = max1, num
elif num > max2:
max2 = num
return (max1 - 1) * (max2 - 1)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.