Leetcode 628. Maximum Product of Three Numbers(Easy)

1.题目

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.

2.思路

先把整数序列进行由小到大的排序。序列中有正有负,三个数的乘积。想要最大,一定有排序后的队列中的最后一个数字。另外两个,要么是前头的两个数(可能是两个负数,相乘得正数),要么是最后一个数字前面的两个数。

3.算法

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int len=nums.length;
        
        int temp1,temp2;
        temp1=nums[0]*nums[1];
        temp2=nums[len-2]*nums[len-3];
        
        return nums[len-1]*(temp1>=temp2?temp1:temp2);
    }
}

4.总结

开始写的时候,忘记了负数的情况。还是要仔细一点。

猜你喜欢

转载自blog.csdn.net/crab0314/article/details/79724118