LeetCode # Array # Easy # 628. Maximum Product of Three Numbers
Given an integer array, find three numbers whose product is maximum and output the maximum product.
题目:给定一个数组,数组长度3-10000,求其中三个数乘积最大的值;(最大乘积不会超过int范围)
思路:这个题和求第三个最大数的思路一样,但是要注意如果有负数,则两个负数乘积为正。所以要用两个变量存储两个最小数。
1 class Solution { 2 public int maximumProduct(int[] nums) { 3 int m = nums.length; 4 if(m == 3){ 5 return nums[0]*nums[1]*nums[2]; 6 } 7 int first= 0,second=0,third=0; 8 int min1 = Integer.MAX_VALUE, min2= Integer.MAX_VALUE; 9 for(int n :nums ){ 10 if(n > first){ 11 third = second; 12 second = first; 13 first = n; 14 }else if(n > second){ 15 third = second; 16 second = n; 17 }else{ 18 if(n > third) { 19 third = n; 20 } 21 } 22 if(n < min1){ 23 min2 = min1; 24 min1 = n; 25 }else if(n < min2){ 26 min2 = n; 27 } 28 } 29 return Math.max(first*second*third,first*min1*min2); 30 } 31 }