0

Possible Duplicate:
Finding three elements in an array whose sum is closest to an given number

You are given an array of integers, A1, A2, ..., An, including negatives and positives, and another integer S. Now we need to find three different integers in the array, whose sum is closest to the given integer S. If there exists more than one solution, any of them is ok. Is there an algorithm to find the three integers in O(n^2) time?

Community
  • 1
  • 1
dee
  • 11
  • 1
  • 7
    We are given? Personally I don't feel like I am given any array. I thought that you were given this array of integers. – Darin Dimitrov Sep 17 '11 at 11:56
  • Seems to be homework. What have you got so far? – Florian Greinacher Sep 17 '11 at 11:58
  • 3
    It's fine to ask about algorithms, and to ask about homework (people here prefer when you are honest about it), but tagging your question `visual-c++` as if someone was going to give you a Visual-C++ program with the thought you have currently put into the problem is ludicrous. – Pascal Cuoq Sep 17 '11 at 11:59

1 Answers1

4

Yes there is. You want to find a, b, c with a+b+c as close as possible to s.

  1. Order the numbers in increasing order.

  2. Try each a-value. For each a-value, do the following steps:

  3. Start with b = the smallest (first) number and c = the largest (last) number. Decrease c, step by step, if that brings a+b+c closer to s.

  4. Then increase b step by step, and each time you increase b, decrease c step by step if that brings a+b+c closer to s.

Johan Råde
  • 18,399
  • 19
  • 62
  • 103
  • 2
    I don't think that this will work in all cases. The difference can be positive or negative (and the numbers to add as well - which is however not relevant to my objection here). So while decreasing c may get you closer for the absolute difference to the expected sum, it may be that after increasing b you'd need to increase c again to get even closer. – Lucero Sep 17 '11 at 12:37
  • @Lucero: The method is correct. If b1 <= b2 and c1 is the best c for b1 and c2 is the best c for b2, then c2 <= c1. – Johan Råde Sep 17 '11 at 14:32