前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 1464. Maximum Product of Two Elements in an Array

Leetcode 1464. Maximum Product of Two Elements in an Array

作者头像
Tyan
发布2022-05-10 08:01:26
2200
发布2022-05-10 08:01:26
举报
文章被收录于专栏:SnailTyanSnailTyan

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

1. Description

Maximum Product of Two Elements in an Array
Maximum Product of Two Elements in an Array

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/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档