Last active
October 21, 2021 10:35
-
-
Save rozer007/02b4b5c4826e01576c1f22906492ba73 to your computer and use it in GitHub Desktop.
pepcoding.com 19/10/21 targetSumPair1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
void input(vector<int> &arr) | |
{ | |
for (int i = 0; i < arr.size(); i++) | |
{ | |
cin >> arr[i]; | |
} | |
} | |
void targetSumPair(vector<int> &arr,int target) | |
{ | |
sort(arr.begin(),arr.end()); | |
int si=0,ei=arr.size()-1; | |
while(si<ei) | |
{ | |
int sum=arr[si]+arr[ei]; | |
if(sum<target) | |
{ | |
si++; | |
}else if(sum>target) | |
{ | |
ei--; | |
} | |
else | |
{ | |
cout<<arr[si]<<", "<<arr[ei]<<endl; | |
si++; | |
ei--; | |
} | |
} | |
} | |
int main() | |
{ | |
int n,target; | |
cin>>n; | |
vector<int> vec(n,0); | |
input(vec); | |
cin>>target; | |
targetSumPair(vec,target); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def targetSumPair(arr,target): | |
arr.sort(); | |
si=0; | |
ei=len(arr)-1; | |
while si<ei: | |
s=arr[si]+arr[ei]; | |
if(s>target): | |
ei-=1; | |
elif(s<target): | |
si+=1; | |
elif s==target: | |
print("%d, %d"%(arr[si],arr[ei])); | |
si+=1; | |
ei-=1; | |
n=int(input()); | |
arr=[]; | |
for i in range(0,n): | |
val=int(input()); | |
arr.append(val); | |
target=int(input()); | |
targetSumPair(arr,target); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
void input(vector<int> &arr) | |
{ | |
for (int i = 0; i < arr.size(); i++) | |
{ | |
cin >> arr[i]; | |
} | |
} | |
void targetSumPair(vector<int> &arr, int target) | |
{ | |
//write your code here | |
} | |
int main() | |
{ | |
int n, target; | |
cin >> n; | |
vector<int> vec(n, 0); | |
input(vec); | |
cin >> target; | |
targetSumPair(vec, target); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def targetSumPair(arr,target): | |
#write your code here | |
n=int(input()); | |
arr=[]; | |
for i in range(0,n): | |
val=int(input()); | |
arr.append(val); | |
target=int(input()); | |
targetSumPair(arr,target); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment