Leetcode 1464. Maximum Product of Two Elements in an Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Product of Two Elements in an Array

2. Solution

解析:Version 1,两层循环遍历,O(N^2)。

  • Version 1
1
2
3
4
5
6
7
8
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
1
2
3
4
5
6
7
8
9
10
11
12
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

Reference

  1. https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
如果有收获,可以请我喝杯咖啡!