working link
more solution=>
https://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
code
https://www.onlinegdb.com/edit/HkS7dTRWP
solution below
*******************************************************************************/
#include <stdio.h>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
void triplet(vector<int> &vec,int sum)
{
//sort the vector
sort(vec.begin(),vec.end());
int i=0;
int j=vec.size()-1;
while(j>=i)
{
if(vec.at(i)+vec.at(i+1)+vec.at(j)==sum)
{
const int a=vec.at(i);
const int b=vec.at(i+1);
const int c=vec.at(j);
std::cout <<a<<"-"<<b<<"-"<<c<< std::endl;
return;
}
//if sum is less than target increase i
else if(vec.at(i)+vec.at(i+1)+vec.at(j)<sum)
{
i++;
}
//if sum is more than target decrease j
else
{
j--;
}
}
}
int main()
{
vector<int> vect={11, 2, 3, 4, 5} ;
int sum=9;
triplet(vect,sum);
return 0;
}
Comments
Post a Comment