leetcode - 1464 Maximum Product of Two Elements in an Array JavaScript Solution

preview_player
Показать описание
like and subscribe :) and share your solution!

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).
Рекомендации по теме
Комментарии
Автор

I love how considerate you are at explaining all the steps you take to get to an answer. This is kind of a random question but I hear some Korean accent in the way you speak. Are you korean by any chance?

samoh
Автор

Hey, nice video !

But actually the intention of this problem is to make us solve it in O(N) or O(logn) (using heapify).
I've posted a solution below (doesn't using heapify) but works in O(N) time.
It makes two passes over the array (to get first and next greatest element), taking into account duplicates.
Then we just return (first-1)*(second-1). (Because sorting can be costly if the array it very large)

Please see below solution:

var maxProduct = function(nums) {

let max=nums[0],
let maxOccurences = 0;

for(let i=0;i<nums.length;i++) {
max = (nums[i]>max)? nums[i] : max
}

for(let i=0;i<nums.length;i++) {
if(nums[i]===max) {
maxOccurences++;
}
}

if(maxOccurences>1) {
nextmax = max;
} else {
for(let i=0;i<nums.length;i++) {
nextmax = (nums[i]>nextmax && nums[i] !== max)? nums[i] : nextmax;
}
}

return (max-1)*(nextmax-1)
};

rajeshseptember