文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
解析:Version 1,两层循环遍历,O(N^2)。
- Version 1
class Solution:
def maxProduct(self, nums: List[int]) -> int:
product = 0
length = len(nums)
for i in range(length):
for j in range(i+1, length):
product = max(product, (nums[i] - 1) * (nums[j] - 1))
return product
解析:Version 2,找到数组里最大的两个元素即可,O(N)。
- Version 2
class Solution:
def maxProduct(self, nums: List[int]) -> int:
x1 = max(nums[0], nums[1])
x2 = min(nums[0], nums[1])
for num in nums[2:]:
if num >= x1:
x2 = x1
x1 = num
elif num > x2:
x2 = num
product = (x1 - 1) * (x2 - 1)
return product