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)
相关推荐
jiaway4 分钟前
【C语言】第四课 指针与内存管理
c语言·开发语言·算法
做就对了66667 分钟前
驱动员工的核心:少谈“大道理”,多解“人心”
职场和发展·职场·管理·团队管理·销售
菩提树下的凡夫8 分钟前
瑞芯微RV1126目标识别算法Yolov8的部署应用
java·算法·yolo
多打代码1 小时前
2025.09.05 用队列实现栈 & 有效的括号 & 删除字符串中的所有相邻重复项
python·算法
j_xxx404_2 小时前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
南莺莺2 小时前
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判别,表达式中的括号是否配对,以字符“\0“作为算术表达式的结束符
c语言·数据结构·算法·
Lris-KK3 小时前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
THMAIL3 小时前
深度学习从入门到精通 - 神经网络核心原理:从生物神经元到数学模型蜕变
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
珍珠是蚌的眼泪3 小时前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦3 小时前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode