Leetcode 1464. Maximum Product of Two Elements in an Array

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1464. Maximum Product of Two Elements in an Array相关的知识,希望对你有一定的参考价值。

文章作者: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

Reference

  1. https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/

以上是关于Leetcode 1464. Maximum Product of Two Elements in an Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1464. Maximum Product of Two Elements in an Array 解题报告

Leetcode 1464. Maximum Product of Two Elements in an Array

Leetcode 1464. Maximum Product of Two Elements in an Array

LeetCode 1464. 数组中两元素的最大乘积

LeetCode刷题1464-简单-数组中两元素的最大乘积

LeetCode刷题1464-简单-数组中两元素的最大乘积