> For the complete documentation index, see [llms.txt](https://blog.yushunchen.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blog.yushunchen.com/algo/two-pointers/two-sum-closest-to-target.md).

# Two Sum - Closest to target

{% embed url="<https://www.lintcode.com/problem/533/>" %}

## Solution 1 (Java)

```java
public class Solution {
    /**
     * @param nums: an integer array
     * @param target: An integer
     * @return: the difference between the sum and the target
     */
    public int twoSumClosest(int[] nums, int target) {
        int minDiff = Integer.MAX_VALUE;
        if (nums == null || nums.length < 2)
            return minDiff;
        Arrays.sort(nums);

        int left = 0, right = nums.length - 1;
        while (left < right) {
            int diff = target - nums[left] - nums[right];
            minDiff = Math.min(minDiff, Math.abs(diff));
            if (diff == 0) return 0;
            if (diff > 0) {
                left++;
            } else {
                right--;
            }
        }
        return minDiff;
    }
}
```

### Notes

* We sort the array first using the built-in method.
* Then, we update the minimum difference when possible and we use the opposite two pointers to keep track of the difference.&#x20;
* Make sure to add absolute value for `diff` as required by the problem.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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.yushunchen.com/algo/two-pointers/two-sum-closest-to-target.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.
