628. Maximum Product of Three Numbers

来源:互联网 发布:文言中乎的用法和意义 编辑:程序博客网 时间:2024/05/13 17:56

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.


Seen this question in a real interview before?

O(n):
public class Solution {    public int maximumProduct(int[] nums) {        int l1 = Integer.MAX_VALUE;int l2 = Integer.MAX_VALUE;int f1 = Integer.MIN_VALUE;int f2 = Integer.MIN_VALUE;int f3 = Integer.MIN_VALUE;for (int i : nums) {if (i > f1) {f3 = f2;f2 = f1;f1 = i;} else if (i > f2) {f3 = f2;f2 = i;} else if (i > f3)f3 = i;if (i < l1) {l2 = l1;l1 = i;} else if (i < l2)l2 = i;}return Math.max(f1 * f2 * f3, f1 * l1 * l2);    }}

O(nlogn):
public class Solution {    public int maximumProduct(int[] nums) {        Arrays.sort(nums);int n = nums.length;int a = nums[0] * nums[1] * nums[n - 1];int b = nums[n - 1] * nums[n - 2] * nums[n - 3];return Math.max(a, b);    }}



原创粉丝点击