LeetCode Daily Question 628. Maximum product of three numbers

628. Maximum product of three numbers

Given an integer array, find the largest product of three numbers in the array, and output this product.

Example 1:

输入: [1,2,3]
输出: 6

Example 2:

输入: [1,2,3,4]
输出: 24

note:

  • The length range of the given integer array is [3,10 4 ], and the range of all the elements in the array is [-1000, 1000].
  • The product of any three numbers in the input array will not exceed the range of 32-bit signed integers.

Method 1: Sort

Problem-solving ideas

It is not difficult to find that the answer can only be produced in two numbers

  1. Multiply the smallest two numbers and the largest number
  2. Multiply the three largest numbers

After sorting, find the corresponding number and multiply it to be OK~

Reference Code

public int maximumProduct(int[] nums) {
    
    
    Arrays.sort(nums);
    int n = nums.length;
    return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 3] * nums[n - 2] * nums[n - 1]);
}

Results of the
Insert picture description here

PS: You can also find these five numbers by traversing once, the pen and ink are almost used up, so I won’t write it~

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/112861778