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)
相关推荐
天才测试猿25 分钟前
Jmeter压测实战:Jmeter二次开发之自定义函数
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·压力测试
guygg8838 分钟前
基于全变差的压缩感知视频图像重构算法
算法·重构·音视频
尋有緣44 分钟前
力扣1327-列出指定时间段内所有的下单产品
leetcode·oracle·数据库开发
VT LI1 小时前
SDF在实时图形渲染中的核心原理与架构创新
算法·sdf·有号距离场
想七想八不如114081 小时前
408操作系统 PV专题
开发语言·算法
天一生水water1 小时前
储层认知→技术落地→产量优化
人工智能·算法·机器学习
明洞日记1 小时前
【VTK手册019】 深入理解 vtkProperty:从几何表达到 PBR 物理渲染
c++·图像处理·算法·vtk·图形渲染
Genevieve_xiao1 小时前
【数据结构与算法】【xjtuse】面向考纲学习(下)
java·数据结构·学习·算法
修炼地1 小时前
代码随想录算法训练营第二十七天 | 56. 合并区间、738.单调递增的数字、968.监控二叉树
c++·算法
仰泳的熊猫1 小时前
1031 Hello World for U
数据结构·c++·算法·pat考试