LeetCode: Maximum Product of Three Numbers Solution
Sort and keep in mind of negative numbersApproach
Sorting any direction (in the post, direction is ascending)
Take product of 3 largest numbers
But there are also negative numbers, so also consider product of 2 lowest numbers
Implementation
1var maximumProduct = function (nums) {2 nums = nums.sort((a, b) => (a > b ? 1 : -1))3 return Math.max(4 nums[0] * nums[1] * nums[nums.length - 1],5 nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]6 )7}
Comments
Loading comments...
Tags
leetcode
array
sorting
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.