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)
相关推荐
xsyaaaan几秒前
leetcode-hot100-普通数组:53最大子数组和-56合并区间-189轮转数组-238除了自身以外数组的乘积-41缺失的第一个正数
leetcode
0 0 03 分钟前
洛谷P4427 [BJOI2018] 求和 【考点】:树上前缀和
开发语言·c++·算法·前缀和
佩奇大王11 分钟前
P593 既约分数
java·开发语言·算法
云泽80815 分钟前
蓝桥杯算法精讲:贪心算法之推公式例题深度剖析
算法·贪心算法·蓝桥杯
客卿12336 分钟前
力扣--组合,子集--回溯法的再探索--总结回溯法
java·算法·leetcode
_日拱一卒38 分钟前
LeetCode(力扣):环形链表
算法·leetcode·链表
做怪小疯子41 分钟前
Leetcode刷题——链表就地反转
算法·leetcode·链表
仟濹1 小时前
【算法打卡day22(2026-03-14 周六)今日算法or技巧:双指针 & 链表】9个题
数据结构·算法·链表·双指针
RechoYit1 小时前
数学建模——评价与决策类模型
python·算法·数学建模·数据分析
地平线开发者1 小时前
地平线 Sparse 多任务参考算法 SparseBevFusionMultitaskOE-V1.0
算法·自动驾驶