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:
- 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.
题目标签:Array, Math
题目给了我们一个nums array,要我们找到最大的三数乘积。
先让我们来看一下几个例子,假设下面的数字是从小到大排序,- 代表负数,+ 代表正数
a. + + + + +
答案:max1 * max2 * max3 最大的三个数字乘积
b. - - + + +
答案:在 max1 * max2 * max3 和 min1 * min2 * max1 里取大的,这里就需要比较一下两边的 2种情况了。
c. - - 0 + +
答案:min1 * min2 * max1, 这里包括0,其实0并不会影响我们的算法。
d. - - - - +
答案:min1 * min2 * max1
e. - - - - -
答案:max1 * max2 * max3, 这里全部都是负数,答案反而变成了三个最大的数字乘积,因为这个情况下,总会是负数,所以要挑最右边三个数字。
这样我们就发现了,最大三个数字乘积,就发生在 最大的三个数字乘积 和 最小的2个数字 * 最大的数字 中。只要维护更新max1, max2, max3, min1, min2 取大的那种情况就可以。
Java Solution:
Runtime beats 91.55%
完成日期:10/18/2017
关键词:Array, Math
关键点:维护更新max1, max2, max3, min1, min2
class Solution { public int maximumProduct(int[] nums) { int max1 = Integer.MIN_VALUE; int max2 = max1; int max3 = max1; int min1 = Integer.MAX_VALUE; int min2 = min1; for(int num: nums) { // take care max if(num > max1) { max3 = max2; max2 = max1; max1 = num; } else if(num > max2) { max3 = max2; max2 = num; } else if(num > max3) max3 = num; // take care min if(num < min1) { min2 = min1; min1 = num; } else if(num < min2) min2 = num; } return Math.max(max1 * max2 * max3, min1 * min2 * max1); } }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
- LeetCode:152_Maximum Product Subarray | 最大乘积连续子数组 | Medium
- leetcode 479. Largest Palindrome Product最大的回文乘积
- LeetCode 152. Maximum Product Subarray(最大乘积)
- LeetCode 318. Maximum Product of Word Lengths(最大单词长度乘积)
- (Java) LeetCode 152. Maximum Product Subarray —— 乘积最大子序列
- Leetcode - Dynamic Programming - 343. Integer Break(划分整数得到最大乘积)
- [LeetCode] Integer Break 切割整数,求取最大乘积
- leetcode628.Maximum Product of Three Numbers三个数的最大乘积
- [LeetCode] 152. Maximum Product Subarray 求最大子数组乘积
- LeetCode-152. Maximum Product Subarray (JAVA)(子数组的最大乘积)
- LeetCode-152:Maximum Product Subarray (乘积最大连续子数组) -- medium
- 【LeetCode151-160】逆转string,最大连续乘积,实现附加功能stack,找到两单链表的交点(精巧)
- 【LeetCode】152. Maximum Product Subarray最大连续子数组乘积
- leetcode_318. Maximum Product of Word Lengths 求两个不相交的字符串的长度乘积的最大值,将字母转换成二进制形式,按位与比较是否有相同字母
- LeetCode:152. Maximum Product Subarray Java 子数组最大乘积
- [LeetCode] Maximum Product Subarray 求最大子数组乘积
- LeetCode 152. Maximum Product Subarray--连续子数组最大乘积
- leetcode 628. Maximum Product of Three Numbers 最大的三个元素之积 + 暴力分析
- [LeetCode] Maximum Product Subarray 求最大子数组乘积
- 【LeetCode-面试算法经典-Java实现】【152-Maximum Product Subarray(子数组的最大乘积)】