假设我们有一个数字列表,我们必须找到两个不同元素的最大乘积。
因此,如果输入类似于[5、3、7、4],则输出为35
为了解决这个问题,我们将遵循以下步骤-
curr_max:= -inf
对于范围在0到nums-1之间的i
如果nums [i] * nums [j]> curr_max,则
curr_max:= nums [i] * nums [j]
对于范围为i + 1的j到nums的大小-1,请执行
返回curr_max
让我们看下面的实现以更好地理解-
class Solution: def solve(self, nums): curr_max = float('-inf') for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] * nums[j] > curr_max: curr_max = nums[i] * nums[j] return curr_max ob = Solution()print(ob.solve([5, 3, 7, 4]))
[5, 3, 7, 4]
输出结果
35