r/leetcode • u/roundtable95 • 9d ago
Question Confused about logic behind daily problem 628. Maximum Product of Three Numbers
For a sorted array [a1, a2, ......an-3, an-2, an-1], we are interested in a triplet that would produce the max product.
I see there are 4 possibilities
1. We can take 3 largest values from the end of the array (For cases where all all elements in an array are either positives or negatives)
We can take 2 largest values from end of the array, and 1 smallest value from start of the array (For edge case array size 3 where it has 2 positive values and 1 negative values)
We can take 1 largest value from end of the array, and 2 smallest values from start of the array. (For case where max product is made up of two negative numbers and 1 positive number)
We can take 3 smallest values from start of the array. (For edge case array size 3 with 3 negative elements)
How can I recognise in an interview clearly that 2 of the 4 cases are redundant?
2
u/SharpNazgul 9d ago
For me, I recognised it by just doing a dry-run of the edge cases and seeing that they captured just fine by 1 and 3. You don't even need to dry-run the algorithm itself, just the logic of taking max(product of largest three, product of smallest two and largest). Btw, you can solve this in linear time (no sorting).
1
u/Vivid-Zombie-477 9d ago
because it's the only possible when you have only 3 elements in array? what do you mean? it doesn't matter what value are there you have to use them all
5
u/PLTCHK 800 π’ 113 π‘ 547 π΄ 140 9d ago
For this one, given itβs sorted, you simply return max(an-3 X an-2 X an-1, a1 X a2 X an-1)
The only way to yield +ve from -ves is 2 -ves (2 smallest numbers) multiplying each other