Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to find the sum of three numbers in a vector that is closest to a given value in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // std::sort

int threeSumClosest(std::vector<int>& nums, int target) {
    std::sort(nums.begin(), nums.end()); // Sort the array
    int closestSum = nums[0] + nums[1] + nums[2]; // Initialize with the first triplet sum

    for (size_t i = 0; i < nums.size() - 2; i++) {
        size_t left = i + 1, right = nums.size() - 1;

        while (left < right) {
            int currentSum = nums[i] + nums[left] + nums[right];

            // Update closestSum if the current sum is closer to the target
            if (std::abs(target - currentSum) < std::abs(target - closestSum)) {
                closestSum = currentSum;
            }

            // Adjust pointers based on the comparison with the target
            if (currentSum < target) {
                ++left;
            } else {
                --right;
            }
        }
    }

    return closestSum;
}

int main() {
    std::vector<int> nums = {-1, 4, 2, 2};
    int target = 4;

    std::cout << "Closest sum: " << threeSumClosest(nums, target) << std::endl;
}

  
  
/*
run:
  
Closest sum: 3
  
*/

 



answered Oct 11, 2025 by avibootz
...