Maximum Product of Two Elements in an Array

easy heap top k array

Problem

Given an array of integers nums, choose two different indices i and j. Return the maximum value of (nums[i] − 1) · (nums[j] − 1).

Inputnums = [3,4,5,2]
Output12
Picking i=1 and j=2 gives (4−1)·(5−1) = 3·4 = 12.
Inputnums = [1,5,4,5]
Output16
The two largest are 5 and 5: (5−1)·(5−1) = 16.

def max_product(nums):
    first = second = 0          # two largest seen so far
    for v in nums:
        if v > first:
            second = first      # old max slides down
            first = v
        elif v > second:
            second = v
    return (first - 1) * (second - 1)
function maxProduct(nums) {
  let first = 0, second = 0;       // two largest seen so far
  for (const v of nums) {
    if (v > first) {
      second = first;              // old max slides down
      first = v;
    } else if (v > second) {
      second = v;
    }
  }
  return (first - 1) * (second - 1);
}
int maxProduct(int[] nums) {
    int first = 0, second = 0;       // two largest seen so far
    for (int v : nums) {
        if (v > first) {
            second = first;          // old max slides down
            first = v;
        } else if (v > second) {
            second = v;
        }
    }
    return (first - 1) * (second - 1);
}
int maxProduct(vector<int>& nums) {
    int first = 0, second = 0;       // two largest seen so far
    for (int v : nums) {
        if (v > first) {
            second = first;          // old max slides down
            first = v;
        } else if (v > second) {
            second = v;
        }
    }
    return (first - 1) * (second - 1);
}
Time: O(n) Space: O(1)