题目链接
    image.png

    1. class Solution {
    2. // 1.排序+分情况 取最大值 11ms,71.55%
    3. public int maximumProduct1(int[] nums) {
    4. Arrays.sort(nums);
    5. int n = nums.length;
    6. return Math.max(nums[0]*nums[1]*nums[n-1],nums[n-1]*nums[n-2]*nums[n-3]);
    7. }
    8. // 2.线性。 一次性找到上面排序的五个值。。。 2ms,99.57%
    9. public int maximumProduct(int[] nums) {
    10. int min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE;
    11. int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE;
    12. for(int n : nums) {
    13. if(n < min1) {
    14. min2 = min1;
    15. min1 = n;
    16. } else if(n < min2) {
    17. min2 = n;
    18. }
    19. if(n > max1) {
    20. max3 = max2;
    21. max2 = max1;
    22. max1 = n;
    23. } else if(n > max2) {
    24. max3 = max2;
    25. max2 = n;
    26. } else if(n > max3) {
    27. max3 = n;
    28. }
    29. }
    30. // System.out.println(min1 + " " + min2 + " " + max3 + " " + max2 + " " + max1);
    31. // 比较两个乘积的大小。
    32. return Math.max(min1*min2*max1, max1*max2*max3);
    33. }
    34. }