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 (numsi-1)*(numsj-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)
相关推荐
wu_ye_m8 分钟前
学习c语言第34天 用函数每次输出+1,链式访问,int和void
c语言·学习·算法
Felomeng14 分钟前
从旧博客出发,向新的世界走去
程序人生·职场和发展
星马梦缘18 分钟前
算法设计与分析 作业三 答案与解析
算法·线性规划·二分图匹配·多元最短路·流网络·bellmanford·匈牙利树算法
微风欲寻竹影20 分钟前
Java数据结构——二叉树(Binary Tree)详解
java·数据结构·算法
想吃火锅100521 分钟前
【leetcode】3.无重复字符的最长字串js版
算法·leetcode·职场和发展
smith成长之旅24 分钟前
08 | Mem0 框架分析: BM25 的 Sigmoid 归一化
数据库·python·算法
dongf201926 分钟前
R 语言随机森林算法
算法·随机森林·r语言
AZaLEan__39 分钟前
图论:拓扑排序
算法·深度优先
悠仁さん40 分钟前
数据结构 排序
数据结构·算法·排序算法
阿文的代码库42 分钟前
机器学习之精确率和召回率的关系
人工智能·算法·机器学习