[英]Find minimum sum of the list optimally using python
我试图解决编码挑战,该挑战指出:
给定列表“ L”和替换数“ k”。
步骤1:在迭代1中,从“ L”中找到任何数字,将其减半并将其舍入为整数。 步骤2:对“ k”操作进行步骤1的迭代,以便最后得到列表“ L”中所有元素的minimum sum
。
例:
L=[1,2,2,3] k=4
[1,2,2,2] replaced 3 by 2 ( round(3/2)=2)
[1,2,2,1] replaced 2 by 1
[1,2,1,1] replaced 2 by 1
[1,1,1,1] replaced 2 by 1
因此,总和为4及其最小值。 注意:数组可能未排序。
我尝试了这种方法:
def fun(L,k):
for i in range(k):
L.sort()
num=round(L[-1]/2)
L[-1]=num
return sum(L)
由于时间复杂,此方法显示“超时”。
有什么最佳方法可以解决此问题。
尝试这个:
nums = [1,2,3,4]
def fun(L, K):
return sum([round(i/2) for i in L])
print(fun(nums, 4))
如果您对此语法感到困惑,请参阅列表理解 。
即使在最坏的情况下,您也只需修改k个最大元素。 让我们把这k个元素称为B。 您可以在O((nk)* k))时间获得那些。 k-largestor-数组中最小的元素
下一个:
现在添加Sum(B)和Sum(L \\ B)
因此,您的总时间约为O(n * k)
这是代码:
def index_min(l):
m = 0
for i in range(len(l)):
if l[i] < l[m]:
m = i
return m
def index_max(l):
m = 0
for i in range(len(l)):
if l[i] > l[m]:
m = i
return m
def func(L,k):
#Get k greatest elements of L
B = L[:k]
rest = []
for element in L[k:]:
inx = index_min(B)
if element > B[inx]:
rest.append(B[inx])
B[inx] = element
else:
rest.append(element)
#Modify B
for i in range(k):
inx = index_max(B)
num = round(B[inx]/2)
B[inx] = num
return sum(B) + sum(rest)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.