LeetCode 1464: Maximum Product of Two Elements in an Array Solution

Master LeetCode problem 1464 (Maximum Product of Two Elements in an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1464. Maximum Product of Two Elements in an Array

Problem Explanation

Explanation

To find the maximum product of two elements in an array, we can simply find the two largest elements in the array and subtract 1 from each before multiplying them together. We can iterate through the array once to find the largest and second largest elements. The time complexity of this approach is O(n) where n is the length of the array, and the space complexity is O(1).

Solution Code

class Solution {
    public int maxProduct(int[] nums) {
        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        
        for (int num : nums) {
            if (num > max1) {
                max2 = max1;
                max1 = num;
            } else if (num > max2) {
                max2 = num;
            }
        }
        
        return (max1 - 1) * (max2 - 1);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1464 (Maximum Product of Two Elements in an Array)?

This page provides optimized solutions for LeetCode problem 1464 (Maximum Product of Two Elements in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1464 (Maximum Product of Two Elements in an Array)?

The time complexity for LeetCode 1464 (Maximum Product of Two Elements in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1464 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1464 in Java, C++, or Python.

Back to LeetCode Solutions