Leetcode 1464. Maximum Product of Two Elements in an Array

2022-05-10 08:01:26 浏览数 (1)

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞