Leetcode 1464. Maximum Product of Two Elements in an Array
Leetcode Problem 1464: 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).
nums?
nums[i] is an integer in the range [1, 10^3].To find the maximum product of (nums[i] - 1) * (nums[j] - 1), the optimal approach is to identify the two largest elements in the array because reducing the maximum numbers by 1 and then multiplying gives the highest product.
first_max) and the second maximum (second_max) numbers.(first_max - 1) * (second_max - 1) and return it.public class Solution {
public int maxProduct(int[] nums) {
// Initialize the first and second maximums
int firstMax = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
// Traverse through the array to find the two largest numbers
for (int num : nums) {
if (num > firstMax) {
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax) {
secondMax = num;
}
}
// Calculate and return the result
return (firstMax - 1) * (secondMax - 1);
}
}
n is the number of elements in nums.Consider nums = [3, 4, 5, 2].
firstMax = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE.firstMax = 3, secondMax = Integer.MIN_VALUE.firstMax = 4, secondMax = 3.firstMax = 5, secondMax = 4.Final product: (5 - 1) * (4 - 1) = 4 * 3 = 12.
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?