我正在尝试解决来自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.
在尝试(不成功)后,我谷歌了解决方案,这个方法有效。
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)
我理解这段逻辑,除了为什么na和nb被赋值为0x7FFFFFFF。看起来它是int32的最大值。有人能帮我解释一下这个数字的意义以及为什么在这里使用它吗?(我本来会使用1001代替)
ans
从未改变其初始常量值?我认为0x7FFF_FFFF除了是最大可能的数字之外没有任何意义,因此保证被数组中的数字覆盖。它比1001更好,因为即使是那些没有正确阅读问题描述的人也能看到它是最大可能的数字。我想这就是全部。 - user234461na
和nb
只是初始化为某个无限版本,以使比较第一次起作用。 - chepner