Leetcode 1464. Maximum Product of Two Elements in an Array
You are given an integer array nums
. The goal is to find the maximum product of two elements in the array. To do this, you pick two different indices i
and j
such that the product ((nums[i] - 1) * (nums[j] - 1)) is maximized, where (i \neq j).
Return the maximum value of ((nums[i] - 1) * (nums[j] - 1)).
max_1
and max_2
are the two largest numbers in the array.max1
and max2
to store the largest and the second-largest elements in the array.max1
and max2
accordingly.Here’s the implementation in C++:
#include <vector>
#include <algorithm>
int maxProduct(std::vector<int>& nums) {
int max1 = 0, max2 = 0;
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
}
return (max1 - 1) * (max2 - 1);
}
max1
and max2
initialized to zero.num
is greater than max1
, we update max2
to be max1
and then set max1
to num
.num
is larger than max2
, update max2
to be num
.The time complexity of this solution is (O(n)), where (n) is the number of elements in the array. This efficiency is because we only need a single pass through the array to determine the two largest elements. The space complexity is (O(1)) as we are using a fixed amount of additional space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?