[LeetCode] 628. Maximum Product of Three Numbers

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.

三个数的最大乘积。

题意是给一个数组,请找出三个数字,使得他们的乘积最大,返回这个最大的乘积。

这是个数学题。如果数组中不存在负数则没什么好说的,直接取数组中最大的三个数,得出乘积即可;但是数组存在负数,所以最大乘积有可能是三个最大的数字的乘积,也有可能是两个最小的负数与一个最大的正数的乘积。

时间O(nlogn)

空间O(1)

Java实现

1 class Solution {
2     public int maximumProduct(int[] nums) {
3         Arrays.sort(nums);
4         int n = nums.length;
5         return Math.max(nums[n - 1] * nums[n - 2] * nums[n - 3], nums[0] * nums[1] * nums[n - 1]);
6     }
7 }

 

LeetCode 题目总结

posted @ 2020-09-12 06:40  CNoodle  阅读(167)  评论(0编辑  收藏  举报