LeetCode-628. Maximum Product of Three Numbers (Java)

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:

Input: [1,2,3]
Output: 6

Example 2:

Input: [1,2,3,4]
Output: 24

Note:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
  2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
-----------------------------------------------------------------------------------------------------------------------------

题意

找到一列数组中,乘积结果最大的三个数。

思路

我的思路是先排序,然后再做处理。因为元素值可能为负值,所以不能简单地从数组末尾开始,往前取三个数。因为数组末尾的元素值组大,
三个数必包含它,然后就剩两个数。当数组头部分元素为负值,则这两个数有可能在头,如果数组为正值,则这两个数在末尾部分。

代码
public class Solution {
    public int maximumProduct(int[] nums) {
        //对数组排序
        Arrays.sort(nums);
		int i=0;
		int j =nums.length-1;
		int count =0;
		int result = 0;
		//排序后,数组最末尾的元素小于等于0,则表示整个数组都为负值
		//那么乘积最大的三个数则在数组末尾
		if(nums[j] <=0){
			if(count <3){
				result = nums[j] * nums[j-1]*nums[j-2];
				count++;
			}		
		}
		//如果数组最末尾的元素大于0,则表示整个数组可能包含正值和负值
		//除数组最末尾元素外,其他两个元素可能在数组末尾部分,可能在数组开始部分
		else{
		    //数组开始部分两个数乘积
			int valueOfFront = nums[i] * nums[i+1];
			//数组末尾两个数乘积
			int valueOfBehind = nums[j-1] * nums[j-2];
			//如果开始部分的乘积大于末尾部分的乘积
			if(valueOfFront > valueOfBehind){
				result = nums[j]* valueOfFront;
			}else{
				result = nums[j] * valueOfBehind;
			}
		}				
		return result;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值