Two pointers · Medium
A batch planner must choose exactly three distinct entries with a combined amount as close as possible to a target. If two different totals are equally close, the smaller total wins. It needs the chosen sum, not the entries or the absolute gap.
Return the closest sum obtainable from three different indexes and choose the smaller sum when distances to the target tie.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], target: integer }
Fields
- nums contains signed integer amounts; target is the desired total. Duplicate amounts remain distinct entries.
Output
Return value
- Return a numeric sum, or null when fewer than three entries exist.
- Three indexes must differ. Break equal absolute-distance ties by the smaller sum.
Constraints
- 0 <= nums.length <= 1500; -1000000 <= nums[i] <= 1000000; -3000000 <= target <= 3000000.
Examples
Example 1
{
"nums": [
-1,
2,
1,
-4
],
"target": 1
}Returns
2Example 2
{
"nums": [
0,
0,
2,
2
],
"target": 3
}Returns
2Required complexity
O(n²) time and O(n) auxiliary space