Train of thought

First, sort the array.

  • If the array is full of non-negative numbers, then the largest three sorted numbers multiplied together are the largest product.

  • If all are non-positive, then the product of the largest three numbers is also the largest product.

  • If there are positive and negative numbers in the array, the maximum product can be either the product of three maximum positive numbers or the product of two minimum negative numbers (i.e., the maximum absolute value) and the maximum positive number.

To sum up, after sorting the array, we find the product of the three largest positive numbers and the product of the two smallest negative numbers and the largest positive numbers respectively, and the maximum value between the two is the answer.

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        return Math.max(nums[len - 1] * nums[len - 2] * nums[len - 3], nums[0] * nums[1] * nums[len - 1]); }}Copy the code