LeetCode刷题之1464. 数组中两元素的最大乘积
我不知道将去向何方,但我已在路上! |
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |
- 题目:
给你一个整数数组 nums
,请你选择数组的两个不同下标 i
和 j
,使 (nums[i]-1)*(nums[j]-1)
取得最大值。
请你计算并返回该式的最大值。
- 示例:
示例 1 :
输入:nums = [3,4,5,2]
输出:12
解释:如果选择下标 i=1 和 j=2(下标从 0 开始),则可以获得最大值,(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12 。
示例 2 :
输入:nums = [1,5,4,5]
输出:16
解释:选择下标 i=1 和 j=3(下标从 0 开始),则可以获得最大值 (5-1)*(5-1) = 16 。
示例 3 :
输入:nums = [3,7]
输出:12
- 提示:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3
- 代码1:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]-1) * (nums[-2]-1)
- 算法说明:
用排序函数sort()
对nums
进行排序,求出最大值和次大值的乘积(nums[-1]-1) * (nums[-2]-1)
,返回结果。
- 代码2:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
i = 0
j = len(nums) - 1
max_val = 0
while i < j:
temp = (nums[i]-1) * (nums[j]-1)
if temp > max_val: max_val = temp
if nums[i] > nums[j]: j -= 1
else: i += 1
return max_val
- 算法说明:
双指针法,初始化最大值max_val = 0
,前后两个指针i = 0
和j = len(nums) - 1
,遍历数组,求出指针索引元素的乘积(nums[i]-1) * (nums[j]-1)
,和最大值进行比较,更新最大值。比较指针元素的大小,更新较小元素的指针。两个指针不满足大小关系,循环结束,返回结果。
- 代码3:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
max_1 = max_2 = 1
for i in range(len(nums)):
if nums[i] >= max_1:
max_2 = max_1
max_1 = nums[i]
continue
if max_1 > nums[i] >= max_2:
max_2 = nums[i]
return (max_1 - 1) * (max_2 - 1)
- 算法说明:
一次遍历法,初始化最大值和次大值max_1 = max_2 = 1
,如果当前元素不小于最大值if nums[i] >= max_1
,将最大值赋值给次大值max_2 = max_1
,将当前元素赋值给最大值max_1 = nums[i]
,继续循环;如果当前元素小于最大值,不小于次大值if max_1 > nums[i] >= max_2
,将当前元素赋值给次大值max_2 = nums[i]
,返回结果(max_1 - 1) * (max_2 - 1)
。