Skip to content

Commit b7883cd

Browse files
Merge pull request #1 from ishikasinha-d/sum-of-three-values
Add sum_of_three values in cpp
2 parents c1eacc3 + bd068c5 commit b7883cd

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Arrays/sum_of_three_values.c++

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Given an array of size n. Your task is to find three values (at distinct positions) whose sum is x.
2+
// (1<=n<=5000, 1<=x<=10^9)
3+
4+
// Input:
5+
// 4 8
6+
// 2 7 5 1
7+
8+
// Output:
9+
// 1 3 4
10+
11+
// Time complexity: O(n^2)
12+
// Concepts Involved: Sorting, Pointers
13+
14+
#include<bits/stdc++.h>
15+
#define fl(i,a,b) for(i=a;i<b;i++)
16+
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
17+
using namespace std;
18+
typedef long long int ll;
19+
20+
int main()
21+
{
22+
fast;
23+
24+
ll n,k, target, l, r; cin>>n>>k;
25+
vector<pair<ll,ll>> a;
26+
pair<ll, ll > p;
27+
28+
for(ll i=0; i<n; i++)
29+
{
30+
cin>>p.first;
31+
p.second=i+1;
32+
a.push_back(p);
33+
}
34+
sort(begin(a), end(a));
35+
36+
for (ll i = 0; i < n; i++)
37+
{
38+
l=0;
39+
r=n-1;
40+
target= k-a[i].first;
41+
while(l<r)
42+
{
43+
if(a[l].first+a[r].first==target && i!=l && l!=r && r!=i)
44+
{
45+
cout<<a[l].second<<" "<<a[r].second<<" "<<a[i].second;
46+
return 0;
47+
}
48+
else if(a[l].first+a[r].first<=target)
49+
l++;
50+
else
51+
r--;
52+
}
53+
54+
}
55+
cout<<"IMPOSSIBLE";
56+
return 0;
57+
}

0 commit comments

Comments
 (0)