use*_*115 7 python algorithm python-2.7
我试图从leetcode解决这个问题,为了方便起见,这里要复制
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.
Run Code Online (Sandbox Code Playgroud)
在(尝试不成功)尝试之后,我搜索了解决方案,这是有效的
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = pa = pb = pc = None
na = nb = 0x7FFFFFFF
for n in nums:
if n > pa:
pa, pb, pc = n, pa, pb
elif n > pb:
pb, pc = n, pb
elif n > pc:
pc = n
if n < na:
na, nb = n, na
elif n < nb:
nb = n
return max(ans, pa * na * nb, pa * pb * pc)
Run Code Online (Sandbox Code Playgroud)
我理解逻辑,除了为什么na和nb被赋值为0x7FFFFFFF.看起来它是int32的最大值.有人可以帮我解释这个数字的意义以及为什么在这里使用它?(我会用1001代替)
在伪代码中,0x7FFFFFFF将被呈现为无穷大(并且None,呈现为负无穷大)。正确性的证明是一个引理,其大意是可以在最大的三个和最小的两个中找到具有最大乘积的三个数字。加/减无穷大用作最小/最大两个/三个值的哨兵值,一旦扫描了前三个值,很快就会被实际值替换。
1001也可以。
| 归档时间: |
|
| 查看次数: |
328 次 |
| 最近记录: |