DEV Community

bengineer
bengineer

Posted on

LeetCode 628: Maximum Product of Three Numbers (Ruby)

Description: https://leetcode.com/problems/maximum-product-of-three-numbers/submissions/

Solution:

def maximum_product(nums)
    nums = nums.sort
    mins_and_max = (nums[0..1] << nums[-1]).reduce(&:*)
    maxs = nums.reverse[0..2].reduce(&:*)

    if mins_and_max > maxs
        return mins_and_max
    else
        return maxs
    end
end
Enter fullscreen mode Exit fullscreen mode

Explanation:

There is only two possibilities here for the maximum product:

  • The 3 numbers are: the greatest positive 3 numbers or
  • The 3 numbers are: 2 of the greatest negative numbers + 1 of the greatest positive number

Solving:

1- Sort the array.

2- Get the greatest 2 negative numbers and the greatest positive number, multiply them.

3- Get the greatest 3 positive numbers and multiply them.

4- Compare the result from step 2 and 3, return the greatest.

Top comments (0)