找到三个数字的最高产品

时间:2015-04-17 22:18:34

标签: python algorithm

给定一系列整数arrayofints,找到最高乘积Highestproduct,您可以从三个整数中获得。 int的输入数组总是至少有三个整数。

所以我已经从arrayofints弹出了三个号码并将其粘贴在highestproduct中:

Highestproduct = arrayofints[:2]
for item in arrayofints[3:]:
    If min(Highestproduct) < item:
        Highestproduct[highestproduct.index(min(Highestproduct))] = item

如果min highestproduct小于项目:将最低数字替换为当前数字。

这最终会产生最高的产品,但显然有更好的解决方案。我的方法有什么问题?我的解决方案是O(n)吗?

5 个答案:

答案 0 :(得分:62)

跟踪两个最小元素和三个最大元素,答案应为min1 * min2 * max1max1 * max2 * max3

要获得3个整数的最大乘积,我们必须选择3个最大元素。然而,有一个问题,我们可以用2分钟的整数替换2个最小的3个最大元素中的2个。如果两个最小的整数都为负数,则其积为正数,因此min1 * min2可能大于max2 * max3(其中max2max3是数组中3个最大元素中最小的2个)。

这将在O(n)时间内运行。

答案 1 :(得分:2)

这个问题有一些问题,在一个涉及正负int的列表中,最大的组合可能是最小的负值,第二个最小的负值,最大的正值或最大的正值,第二大的正值和第三个值;

例如,-5,-1,1,2,3的列表应该返回15,但是当列表中只有负值时,这不起作用,而不是选择最小的负整数,大的组合实际上是三个最大的负值,例如:-5,-4,-3,-2,-1应返回-6。对此进行编码的简单方法就是存储三个最大的正值(将0视为正值),

当我们通过数组时,三个最小的负值和三个最大的负值,然后我们尝试这九个数字的所有组合并获得最大值。这只需要O(n)时间和O(1)空间。

答案 2 :(得分:2)

这是程序的C ++实现,运行时间为O(N):

#define size 5
int A[size] = {5,4,5,10,-6};

int highest_product_of_3()
{
    int highest = max(A[0],A[1]);
    int lowest = min(A[0],A[1]);

    int highestProductOf2 = A[0]*A[1];
    int lowestProductOf2 = A[0]*A[1];

    int highestProductOf3 = A[0]*A[1]*A[2];

    for (int i=2;i<size;i++)
    {
        int current = A[i];

        // Max of 3 values:
        //                  highest_product_of_3            OR
        //                  current*highestProductOf2       OR
        //                  current*lowestProductOf2

        highestProductOf3 = max(max(highestProductOf3, current*highestProductOf2),
                                current*lowestProductOf2);

        highestProductOf2 = max(max(highestProductOf2, current*highest),
                                current*lowest);

        lowestProductOf2 = min(min(lowestProductOf2, current*highest),
                                current*lowest);

        highest = max(highest, current);        // update highest

        lowest = min(lowest, current);          // update lowest
    }


    return highestProductOf3;
}

答案 3 :(得分:1)

如果您先排序Sub RFC_DEEP_TABLE() Dim sapConn As Object Set sapConn = CreateObject("SAP.Functions") If sapConn.Connection.Logon(0, False) <> True Then MsgBox "Cannot Log on to SAP" End If Dim objRfcFunc As Object Set objRfcFunc = sapConn.Add("STFC_DEEP_TABLE") With objRfcFunc .Exports.Item("IMPORT_TAB").value("STR") = "X" 'Objectvariable oder With-Blockvariable nicht festgelegt End With If objRfcFunc.Call = False Then MsgBox objRfcFunc.Exception End If End Sub ,则最差的运行时间为arrayofints而不是O(n log n)(即不太快)。但代码真的很短。那么朋友之间有什么O(n)呢?

log n

(要清楚的是,排序不需要明确跟踪三个最高数字,三个最低数字 - 这些是类似排序的操作,但比排序整个列表便宜。)

答案 4 :(得分:1)

这种方法基本上适用于任意数量的元素,更不用说3.想法是先对数组进行排序,然后取最后一个和第二个最后一个元素的乘积。这可以在python中实现:

def pr(arr, n):
    n = len(arr)
    arr.sort()
    a = {}

    r = arr[n-1]
    s = arr[n-2]
    return {r, s}

arr = [1, 4, 3, 6, 7, 0]
q = pr(arr, 6)
print(q)

这将打印出产品最高的元素集。

相关问题