Solving Maximum Product Of Two Elements In An Array
For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem!
In simpler terms, the question is asking us to create a function that would pick two numbers (i and j
) that when subtracted by 1 and multiplied to each other it can return the maximum product. The examples do a great job of showing what the input and outputs should be for this problem. For example #1, we can see that the output is 12 because after iterating through the entire array, the function chose numbers 4 and 5 since they were the highest numbers in the array. From there, numbers 4 and 5 were plugged in into this equation (nums[i] — 1) * (nums[j] — 1)
. Now the equation looks like this (4–1) * (5–1)
and our answer ends up being 12. Now that we went over what the problem is asking us to do, let’s do some pseudo code!
The problem already gives us a few hints on how the structure for this function should be. We know that nums
is the array that we have to input, and the question is asking us to return the equation (nums[i]-1) * (nums[j]-1)
. Here’s the pseudo coding that I did for this problem:
As stated on lines 2 and 3 from the screen shot above, I need to create variables that represent the max numbers. I also need to return the equation. Here’s what the code looks so far:
Next, We need to iterate over the nums
array to then change the values of iMax
and jMax
. Since we need to find the max values for both i
and j
, I recommend using Math.max()
. Here’s what the full solution looks like:
Changing the value of jMax
was easy, but I was having issues with changing the value of iMax
. At first I thought that iMax
was supposed to be the max number between 0 and jMax
. After trying out different methods, I realized that the second parameter for Math.max()
on line 11 should be the minimum number between the current number(num
) and jMax
! If we use the example array on line 20, this is what iMax
and jMax
look like during the for of
loop:
We can see here that numbers 4 (iMax
) and 5 (jMax
) remain the largest numbers towards the end of the for of
loop. The number 12 on the bottom of the picture is the correct answer when plugging in numbers 4 and 5 in the equation (iMax-1) * (jMax-1)
.
Here are different types of edge cases along with the results to show that this function actually works:
Here’s the runtime and memory usage when submitting on LeetCode:
I hope this blog was helpful! Please reach out if there are more solutions that can be more efficient! For more info on for of
loops, Math.max()
and Math.min()
, checkout the resource section below!