简体   繁体   English

给定一个具有最大和的数组,找到两个产生最大和但不超过最大值的数字

[英]Given an array with maximum sum, locate two number which produce the maximum sum without exceeding the maximum

I have the following code that counts the number of pairs in an array that have a sum below the maximum,我有以下代码计算数组中总和低于最大值的对数,

def findPairs(arr, x):
 
    l = 0; r = len(arr)-1
    result = 0
 
    while (l < r):
     
        if (arr[l] + arr[r] < x):
         
            result += (r - l)
            l += 1
         

        else:
            r -= 1
 
    return result
     
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
x = 7
print(findPairs(arr, x))

I need to edit it in order to return a list of the pair with the maximum sum not exceeding the maximum parameter (x).我需要对其进行编辑以返回最大总和不超过最大参数 (x) 的对列表。 If there are multiple pairs with the maximum sum then one pair is chosen at random如果有多对具有最大总和,则随机选择一对

You can use the itertools.combinations method to get all possible combinations of a list.您可以使用itertools.combinations方法获取列表的所有可能组合。

from itertools import combinations

def findPair(arr):
    allcomm = combinations(arr,2)
    allcomm = filter(lambda e:sum(e)<=max(arr),allcomm)

    return max(allcomm,key=sum)

        

arr = [1, 2, 3, 4, 5, 6, 7, 8]


print(findPair(arr))

output output

(1, 7)

  1. First I use itertools.combination method to the all possible combination of an array.首先,我使用itertools.combination方法对数组的所有可能组合。
  2. I use the filter method to get only the pair whose sum is less than the max number in the arr.我使用filter方法仅获取总和小于 arr 中的最大数的对。
  3. Then I use the max function to get the maximum sum pair in the allcomm array.然后我使用max function 来获得allcomm数组中的最大和对。

Without additional modules (which would potentially make the implementation more efficient) you could just do this:如果没有其他模块(这可能会使实现更高效),您可以这样做:

def find_pairs(arr, m):
    c = 0
    pair = None
    for i, x in enumerate(arr[:-1]):
        for y in arr[i+1:]:
            if x + y < m:
                c += 1
                pair = x, y
    return c, pair

arr = [1, 2, 3, 4, 5, 6, 7, 8]
m = 7

print(find_pairs(arr, m))

Output: Output:

(6, (2, 4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM