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)
相关推荐
Xの哲學5 分钟前
Linux自旋锁深度解析: 从设计思想到实战应用
linux·服务器·网络·数据结构·算法
晚风吹长发9 分钟前
深入理解Linux中用户缓冲区,文件系统及inode
linux·运维·算法·链接·缓冲区·inode
程序员-King.17 分钟前
day131—链表—反转链表Ⅱ(区域反转)(LeetCode-92)
leetcode·链表·贪心算法
cwplh18 分钟前
DP 优化一:单调队列优化 DP
算法
Halo_tjn19 分钟前
基于Java的相关知识点
java·开发语言·windows·python·算法
CoovallyAIHub23 分钟前
英伟达CES 2026炸场:没有新显卡,却掏出了让全球AI公司彻夜难眠的“算力核弹”
深度学习·算法·计算机视觉
圣保罗的大教堂25 分钟前
leetcode 2943. 最大化网格图中正方形空洞的面积 中等
leetcode
独自破碎E44 分钟前
包含min函数的栈
android·java·开发语言·leetcode
wregjru44 分钟前
【C++】2.9异常处理
开发语言·c++·算法
CoovallyAIHub1 小时前
如何用10%的标注数据,达到可媲美全监督模型的性能?AAAI 2026论文揭秘BCSI三大创新设计
深度学习·算法·计算机视觉