LeetCode Maximum Product of Three Numbers
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Maximum Product of Three Numbers相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/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:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- 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 }
以上是关于LeetCode Maximum Product of Three Numbers的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 152. Maximum Product Subarray
C#解leetcode 152. Maximum Product Subarray
Maximum Product Subarray Leetcode
[动态规划] leetcode 152 Maximum Product Subarray