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)
相关推荐
代码小将2 小时前
Leetcode209做题笔记
java·笔记·算法
Musennn3 小时前
leetcode 15.三数之和 思路分析
算法·leetcode·职场和发展
CM莫问5 小时前
<论文>(微软)避免推荐域外物品:基于LLM的受限生成式推荐
人工智能·算法·大模型·推荐算法·受限生成
康谋自动驾驶6 小时前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈7 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java8 小时前
R-tree详解
java·算法·r-tree
MarkHard1238 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
一只鱼^_9 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼9 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程9 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法