Skip to content

1464. Maximum Product of Two Elements in an Array 👍

Approach 1: Straigtforward

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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)

Approach 2: C++ Fun

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int maxProduct(vector<int>& nums) {
    const auto maxIt1 = ranges::max_element(nums);
    *maxIt1 *= -1;
    const int max2 = ranges::max(nums);
    *maxIt1 *= -1;
    return (*maxIt1 - 1) * (max2 - 1);
  }
};