# 3 Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array

> S = {-1 2 1 -4}, and target = 1

The sum that is closest to the target is 2.

> (-1 + 2 + 1 = 2)

{% tabs %}
{% tab title="Scala" %}

```scala
def threeSumClosest(nums: Array[Int], target: Int): Int = {
  nums.length match {
    case l if l < 3 => throw new Error("not enough numbers")
    case l if l == 3 => nums.sum
    case _ => {
      scala.util.Sorting.quickSort(nums)
      var ret = Int.MaxValue
      for (i <- 0 until nums.length) {
        var j = i + 1
        var k = nums.length - 1
        while (j < k) {
          val current = nums(j) + nums(k) + nums(i)
          if (current == target) return target
          else if (math.abs(current - target) < math.abs(ret - target)) {
            ret = current
          }
          if (current > target) k -= 1
          if (current < target) j += 1
        }
      }
      ret
    }
  }
}

threeSumClosest(Array(1, 2, 3), 9)
threeSumClosest(Array(23, 3, 5, 1, 2), 9)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/3sum-closest.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
