You're a treasure hunter exploring an ancient cave filled with numbered crystals. Your mission? Find the perfect combination of exactly three crystals whose combined power level gets as close as possible to your target magical energy!
Given an array nums of integers representing crystal power levels and a target energy value, find three crystals at different positions whose sum is closest to the target. Return the sum of these three crystals.
Example: With crystals [-1, 2, 1, -4] and target 1, the combination [-1 + 2 + 1 = 2] gets closest to our target of 1.
Note: Each input is guaranteed to have exactly one optimal solution - no ties!
Input & Output
Visualization
Time & Space Complexity
Three nested loops each running up to n times
Only using a few variables to track the closest sum
Constraints
- 3 โค nums.length โค 1000
- -1000 โค nums[i] โค 1000
- -104 โค target โค 104
- Guaranteed to have exactly one solution