You are given an array of n integers, and your task is to find two values (at distinct positions) whose sum is x.
Example:
Input: n = 4, sum = 8, arr = {2, 7, 5, 1}
Output: 4 2 (or 2 4)
Approach
C++
#include <bits/stdc++.h>using namespace std;void sumOfTwoValues(int n, int sum, vector<int> &arr){vector<pair<int, int>> vec;for (int i = 0; i < n; i++)vec.push_back({arr[i], i + 1});sort(vec.begin(), vec.end());int i = 0, j = n - 1;int flag = 0;while (i < j){if (vec[i].first + vec[j].first == sum){flag = 1;cout << vec[i].second << " " <<vec[j].second << "\n";break;}else if (vec[i].first + vec[j].first > sum){j--;}else{i++;}}if (flag == 0)cout << "IMPOSSIBLE\n";}int main(){int n = 4, sum = 8;vector<int> arr = {2, 7, 5, 1};sumOfTwoValues(n, sum, arr);return 0;}
No comments:
Post a Comment