LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [interesting question] find an element which is sum of two other elements (https://www.linuxquestions.org/questions/programming-9/%5Binteresting-question%5D-find-an-element-which-is-sum-of-two-other-elements-453069/)

George2 06-09-2006 01:09 AM

[interesting question] find an element which is sum of two other elements
 
--------------------------------------------------------------------------------

Hello everyone,


I am discussing with my friends about an interesting question about find the maximum element in a set, which is the sum of two other elements.

For example, in set {1, 2, 3, 5, 8, 10}, the answer is 10 (10 = 8 + 2),
which is the maximum element we can find, and it is the sum of two
other elements (8 and 2) in the set.

Currently, I only have brute-force solution. Sorting the set, which takes O(nlgn) time, then enumerate them one by one to find whether two elements can sum up to the maximum element (if the most maximum element does not meet the condition, move to the second largest one), which takes O(n^2) time, so the total time complexity is O(n^2).

I am wondering whether any one have better ideas?


thanks in advance,
George

elyk1212 06-09-2006 01:57 AM

I don't know for sure, but my idea would be to have a set with all permutated results (all possible add combinations) and keep this for your checks. Not sure if that would help, really.

This is probability Combinations.. so....
BigTheta( N!/(N-R)!) ?

Depends on how large N is...? In this case, 6!/(6-2)! => 6*5 = 30. So the other case was O(N^2) = 6^2 = 36, thus I think it saves some time on the check, in this example. But it could become larger as more checks are necissary. You will need to iterate through all combos found for each max found. Sort of a O(NM). Where M = BigTheta( N!/(N-R)!).

graemef 06-09-2006 06:07 AM

I believe that the formula gave was for permutations and as you said you only need combinations, so your Big Oh would be (N!/(N-R)!R!) for R = 2 that will give you N(N-1)/2 which is significantly better than N^2, although the Big Oh will be the same.

But I agree with the approach of sort the original list, calculate the combinations, compare.

elyk1212 06-09-2006 12:48 PM

You are right. Should be: N!/[(N-R)!R!].

But that should be BigTheta, I think, as that is the asymptotic lower, and upper bound. There is no worst or best case of combination variance, there only is X number of combos, which will not change (N held constant). So f(C) will always take C!/[(C-2)!2!], best and worst case.

Not that it matters, really.


All times are GMT -5. The time now is 06:53 PM.