|
| 1 | +# 1464. Maximum Product of Two Elements in an Array |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: Array, Sorting, Heap (Priority Queue). |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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)`. |
| 10 | + |
| 11 | +Example 1: |
| 12 | + |
| 13 | +``` |
| 14 | +Input: nums = [3,4,5,2] |
| 15 | +Output: 12 |
| 16 | +Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. |
| 17 | +``` |
| 18 | + |
| 19 | +Example 2: |
| 20 | + |
| 21 | +``` |
| 22 | +Input: nums = [1,5,4,5] |
| 23 | +Output: 16 |
| 24 | +Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. |
| 25 | +``` |
| 26 | + |
| 27 | +Example 3: |
| 28 | + |
| 29 | +``` |
| 30 | +Input: nums = [3,7] |
| 31 | +Output: 12 |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +**Constraints:** |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +- `2 <= nums.length <= 500` |
| 40 | + |
| 41 | +- `1 <= nums[i] <= 10^3` |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +## Solution |
| 46 | + |
| 47 | +```javascript |
| 48 | +/** |
| 49 | + * @param {number[]} nums |
| 50 | + * @return {number} |
| 51 | + */ |
| 52 | +var maxProduct = function(nums) { |
| 53 | + if (nums.length === 2) { |
| 54 | + return (nums[0] - 1) * (nums[1] - 1); |
| 55 | + } |
| 56 | + var minNegativeNum = 0; |
| 57 | + var secondMinNegativeNum = 0; |
| 58 | + var maxPositiveNum = 0; |
| 59 | + var secondMaxPositiveNum = 0; |
| 60 | + for (var i = 0; i < nums.length; i++) { |
| 61 | + var num = nums[i] - 1; |
| 62 | + if (num < minNegativeNum) { |
| 63 | + secondMinNegativeNum = minNegativeNum; |
| 64 | + minNegativeNum = num; |
| 65 | + } else if (num < secondMinNegativeNum) { |
| 66 | + secondMinNegativeNum = num; |
| 67 | + } else if (num > maxPositiveNum) { |
| 68 | + secondMaxPositiveNum = maxPositiveNum; |
| 69 | + maxPositiveNum = num; |
| 70 | + } else if (num > secondMaxPositiveNum) { |
| 71 | + secondMaxPositiveNum = num; |
| 72 | + } |
| 73 | + } |
| 74 | + return Math.max( |
| 75 | + minNegativeNum * secondMinNegativeNum, |
| 76 | + maxPositiveNum * secondMaxPositiveNum, |
| 77 | + ); |
| 78 | +}; |
| 79 | +``` |
| 80 | + |
| 81 | +**Explain:** |
| 82 | + |
| 83 | +nope. |
| 84 | + |
| 85 | +**Complexity:** |
| 86 | + |
| 87 | +* Time complexity : O(n). |
| 88 | +* Space complexity : O(1). |
0 commit comments