Nuggets team number online, help you Offer impromptu! Click for details
I. Title Description:
Given an integer array nums, find the largest product of three numbers in the array and print the product.
Example 1:
Input: nums = [1,2,3] output: 6
Example 2:
Input: nums = [1,2,3,4] output: 24
Example 3:
Input: nums = [-1,-2,-3] Output: -6
Tip:
- 3 <= nums.length <= 104
- -1000 <= nums[i] <= 1000
Link: leetcode-cn.com/problems/ma…
Ii. Analysis of Ideas:
1. If the array is all positive, the result is the product of the largest three numbers
2. If there is a negative number, the result is still the product of the largest three numbers
3. If there are more than two negative numbers, the result may be the smallest two negative numbers multiplied by the largest positive number or the product of the largest three numbers
4. If they are all negative numbers, the result is the product of the three largest numbers
So you just compare the product of the largest three numbers to the product of the smallest two numbers and the largest number
Iii. AC Code:
var maximumProduct = function(nums) {
nums.sort((a, b) => a - b)
let len = nums.length
let res1 = 1
let res2 = 1
for(let i = 1; i <= 3; i++) {
res1 *= nums[len - i]
}
res2 = nums[0] * nums[1] * nums[len - 1]
return Math.max(res1, res2)
};
Copy the code
Iv. Summary:
Analyze a variety of possible situations first, and then find out the rules can be solved! 14 I finally liver finished! happy
This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions