首页 > 其他 > 详细

LeetCode Maximum Product of Three Numbers

时间:2017-09-13 14:50:19      阅读:286      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/maximum-product-of-three-numbers/description/

题目:

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.

题解:

最大的product只有两种情况, max1*max2*max3 和 max1*min1*min2. iterate遍array 更新这几个值 最后比较两者间选大的.

Time Complexity: O(nums.length). Space: O(1).

AC Java:

 1 class Solution {
 2     public int maximumProduct(int[] nums) {
 3         if(nums == null || nums.length < 3){
 4             throw new IllegalArgumentException("There are less than 3 elements in given array.");
 5         }
 6         
 7         int min1 = Integer.MAX_VALUE;
 8         int min2 = Integer.MAX_VALUE;
 9         
10         int max1 = Integer.MIN_VALUE;
11         int max2 = Integer.MIN_VALUE;
12         int max3 = Integer.MIN_VALUE;
13         
14         for(int n : nums){
15             if(n > max1){
16                 max3 = max2;
17                 max2 = max1;
18                 max1 = n;
19             }else if(n > max2){
20                 max3 = max2;
21                 max2 = n;
22             }else if(n > max3){
23                 max3 = n;
24             }
25             
26             if(n < min1){
27                 min2 = min1;
28                 min1 = n;
29             }else if(n < min2){
30                 min2 = n;
31             }
32         }
33         
34         return Math.max(max1*max2*max3, max1*min1*min2);
35     }
36 }

类似Maximum Product Subarray.

LeetCode Maximum Product of Three Numbers

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/7514530.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!