Find Four Elements That Sums To A Given Value
fgdf
Problem Statement
You are given an array/list 'ARR' of ‘N’ integers and an integer value ‘TARGET’. You need to check whether there exist four numbers (ARR[i], ARR[j], ARR[k], ARR[l]) such that (0 <= i < j < k < l < N) and ARR[i] + ARR[j] + ARR[k] + ARR[l] = 'TARGET'.
Note:
Input Format:
Output Format:
Note:
Constraints:
Sample Input 1:
Sample Output 1:
Explanation For Sample Input 1:
Sample Input 2:
Sample Output 2:
The solution to the Above Question is -
#include<bits/stdc++.h>
string fourSum(vector<int> arr, int target, int n) {
// Write your code here.
unordered_map<int,pair<int,int>> m;
for(int i=0;i<arr.size();i++)
{
for(int j=i+1;j<n;j++)
{
m[arr[i]+arr[j]]=make_pair(i,j);
}
}
for(int i=0;i<arr.size();i++)
{
for(int j=i+1;j<n;j++)
{
int x=arr[i]+arr[j];
if(m.find(target-x)!=m.end())
{
pair<int,int> p=m[target-x];
if(i!=p.first && i!=p.second && j!=p.first && j!=p.second)
return "Yes";
}
}
}
return "No";
}
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.