-
Notifications
You must be signed in to change notification settings - Fork 13
/
TripletSum.cpp
57 lines (53 loc) · 1.8 KB
/
TripletSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
int pairSum(int *arr, int startIndex, int endIndex, int num)
{
int numPair = 0;
while (startIndex < endIndex)
{
if (arr[startIndex] + arr[endIndex] < num)
{
startIndex++;
}
else if (arr[startIndex] + arr[endIndex] > num)
{
endIndex--;
}
else
{
int elementAtStart = arr[startIndex];
int elementAtEnd = arr[endIndex];
if (elementAtStart == elementAtEnd)
{
int totalElementsFromStartToEnd = (endIndex - startIndex) + 1;
numPair += (totalElementsFromStartToEnd * (totalElementsFromStartToEnd - 1) / 2);
return numPair;
}
int tempStartIndex = startIndex + 1;
int tempEndIndex = endIndex - 1;
while (tempStartIndex <= tempEndIndex && arr[tempStartIndex] == elementAtStart)
{
tempStartIndex += 1;
}
while (tempEndIndex >= tempStartIndex && arr[tempEndIndex] == elementAtEnd)
{
tempEndIndex -= 1;
}
int totalElementsFromStart = (tempStartIndex - startIndex);
int totalElementsFromEnd = (endIndex - tempEndIndex);
numPair += (totalElementsFromStart * totalElementsFromEnd);
startIndex = tempStartIndex; endIndex = tempEndIndex;
}
}
return numPair;
}
int tripletSum(int *arr, int n, int num)
{
sort(arr, arr + n);
int numTriplets = 0;
for (int i = 0; i < n; i++)
{
int pairSumFor = num - arr[i];
int numPairs = pairSum(arr, (i + 1), (n - 1), pairSumFor);
numTriplets += numPairs;
}
return numTriplets;
}