#C4315. Closest Sum to Target

    ID: 47840 Type: Default 1000ms 256MiB

Closest Sum to Target

Closest Sum to Target

Given an array of N integers and a target integer, your task is to find three integers in the array such that their sum is as close as possible to the target. More formally, given an array \(A = [a_1,a_2,\dots,a_N]\) and a target \(T\), find three integers \(a_i, a_j, a_k\) (with \(i < j < k\)) such that the absolute difference \(|a_i + a_j + a_k - T|\) is minimized. It is guaranteed that there will be exactly one unique solution.

inputFormat

The input is provided via standard input (stdin) and consists of three lines:

  • The first line contains an integer \(N\) indicating the number of elements in the array.
  • The second line contains \(N\) space-separated integers representing the array elements.
  • The third line contains an integer representing the target value \(T\).

outputFormat

Output the sum of the three integers that is closest to the target. The output should be printed to standard output (stdout).

## sample
4
-1 2 1 -4
1
2