leetcode - 1464. Maximum Product of Two Elements in an Array

Description

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1:

复制代码
Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

复制代码
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

复制代码
Input: nums = [3,7]
Output: 12

Constraints:

复制代码
2 <= nums.length <= 500
1 <= nums[i] <= 10^3

Solution

Brute Force

Time complexity: o ( n 2 ) o(n^2) o(n2)

Space complexity: o ( 1 ) o(1) o(1)

Math Trick

The largest result must be the product of the largest element and second largest element. So go through the list and find out the largest and second largest element.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

Math Trick

python3 复制代码
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        res = 0
        p1, p2 = 0, 0
        for each_num in nums:
            if each_num > p1:
                p2 = p1
                p1 = each_num
            elif each_num > p2:
                p2 = each_num
        return (p1 - 1) * (p2 - 1)
相关推荐
甄心爱学习13 分钟前
KMP算法(小白理解)
开发语言·python·算法
wen__xvn35 分钟前
牛客周赛 Round 127
算法
大锦终37 分钟前
dfs解决FloodFill 算法
c++·算法·深度优先
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 200 题:岛屿数量
算法·leetcode·职场和发展
苦藤新鸡1 小时前
14.合并区间(1,3)(2,5)=(1,5)
c++·算法·leetcode·动态规划
猫头虎1 小时前
2026年1月18日11时博客之星投票数据TOP100总排名预测:全网投票总数突破一万大关
程序人生·职场和发展·创业创新·业界资讯·程序员创富·csdn·博客之星
程序员-King.1 小时前
day145—递归—二叉树的右视图(LeetCode-199)
算法·leetcode·二叉树·递归
漫随流水1 小时前
leetcode算法(112.路径总和)
数据结构·算法·leetcode·二叉树
过期的秋刀鱼!1 小时前
机器学习-带正则化的成本函数-
人工智能·python·深度学习·算法·机器学习·逻辑回归
ScilogyHunter1 小时前
前馈/反馈控制是什么
算法·控制