From ad3ea6b1900e8bfbc320001301e9514955ade394 Mon Sep 17 00:00:00 2001 From: kkomalk <71619994+kkomalk@users.noreply.github.com> Date: Sun, 31 Oct 2021 18:07:06 +0530 Subject: [PATCH] Create 3 Sum Problem of IB Solution of 3 Sum Problem of IB in CPP --- 3 Sum Problem of IB | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 3 Sum Problem of IB diff --git a/3 Sum Problem of IB b/3 Sum Problem of IB new file mode 100644 index 0000000..847cfbb --- /dev/null +++ b/3 Sum Problem of IB @@ -0,0 +1,50 @@ +Problem Description : + + Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. + + Return the sum of the three integers. + + Assume that there will only be one solution + + Example: + + given array S = {-1 2 1 -4}, + + and target = 1. + + The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) + + +Solution : + + +int Solution::threeSumClosest(vector &A, int B) { + sort(A.begin(), A.end()); + + int i, j, sum, n = A.size(); + int M = INT_MIN, m = INT_MAX; + + for(int k = 0; k < n; k++){ + i = k+1; + j = n-1; + sum = B - A[k]; + while(i < j){ + if(A[i] + A[j] == sum){ + return B; + } + else if(A[i] + A[j] < sum){ + M = max(M, A[i] + A[j] + A[k]); + i++; + } + else{ + m = min(m, A[i] + A[k] + A[j]); + j--; + } + } + } + + long long a = (long long)B - (long long)M; + long long b = (long long)m - (long long)B; + + return (a < b) ? M : m; +}