如何在列表中找到两个元素的最大乘积?

编程入门 行业动态 更新时间:2024-10-25 08:18:11
本文介绍了如何在列表中找到两个元素的最大乘积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在hackerrank竞赛中尝试了一个有趣的问题,然后出现了这个问题. 我为此使用了itertools,这是代码:

I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:

import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertoolsbinations(l,2): if max < (a*b): max = (a*b) print(max)

他们还有其他有效的方法吗?当我在某些无法访问的测试用例上遇到超时错误时(这是一次小竞赛).

Is their any other efficient way than this? As I am getting time out error on some test cases which I cant access (as its a small contest).

推荐答案

这里是遵循@User_Targaryen逻辑的实现. heapq 返回列表中的2个最大和2个最小的数字, mul operator 返回这两个数字对的乘积,而max返回这两个产品中最大的一个.

Here is an implementation following @User_Targaryen's logic. heapq returns the 2 largest and 2 smallest numbers in the list, mul operator returns the products of these 2 pairs of numbers, and max returns the largest of these 2 products.

>>> import heapq >>> from operator import mul >>> l = [2,40,600,3,-89,-899] >>> max(mul(*heapq.nsmallest(2,l)),mul(*heapq.nlargest(2,l))) 80011 # -899*-89 = 80011

更多推荐

如何在列表中找到两个元素的最大乘积?

本文发布于:2023-11-30 12:15:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘积   元素   两个   如何在   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!