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)
相关推荐
旺小仔.21 分钟前
双指针和codetop复习
数据结构·c++·算法
jingfeng51439 分钟前
C++ STL-string类底层实现
前端·c++·算法
雲墨款哥2 小时前
JS算法练习-Day10-判断单调数列
前端·javascript·算法
FPGA2 小时前
CRC校验原理及其FPGA实现
算法
Jina AI2 小时前
回归C++: 在GGUF上构建高效的向量模型
人工智能·算法·机器学习·数据挖掘·回归
程序员曦曦2 小时前
10:00开始面试,10:06就出来了,问的问题有点变态。。。
自动化测试·软件测试·功能测试·程序人生·面试·职场和发展
Coovally AI模型快速验证2 小时前
YOLO、DarkNet和深度学习如何让自动驾驶看得清?
深度学习·算法·yolo·cnn·自动驾驶·transformer·无人机
luoqice2 小时前
linux下找到指定目录下最新日期log文件
linux·算法
楽码2 小时前
底层技术SwissTable的实现对比
数据结构·后端·算法
fffcccc11122 小时前
初级背包问题,层层剖析为什么这样做。最好需要自己推演一遍。
算法