Hi,
I am currently working on Sum of Two values, and I am not sure when to increment i and j in the while loop. I tried to do a for loop, but it gave me a time limit error.
This is my code:
#include <bits/stdc++.h>
using namespace std;
#define setIO() ios_base::sync_with_stdio(false); cin.tie(NULL);
const int MAX_N = 2e5;
int num_of_numbers = 0;
int desired_sum = 0;
unsigned long numbers[MAX_N];
void solve() {
setIO();
cin >> num_of_numbers;
cin >> desired_sum;
vector<pair<int, int>> ans;
for (int i = 0; i < num_of_numbers; i++) {
cin >> numbers[i];
}
for (int i = 0; i < num_of_numbers; i++) {
for (int j = i + 1; j < num_of_numbers; j++) {
if (numbers[i] + numbers[j] == desired_sum) {
ans.push_back(make_pair(i + 1, j + 1));
break;
}
}
}
if (ans.size() >= 1) {
cout << ans[0].first << " " << ans[0].second << endl;
} else {
cout << "IMPOSSIBLE" << endl;
}
}
void solve_optimized() {
setIO();
cin >> num_of_numbers;
cin >> desired_sum;
vector<pair<int, int>> ans;
for (int i = 0; i < num_of_numbers; i++) {
cin >> numbers[i];
}
sort(numbers, numbers + num_of_numbers);
int i = 0;
int j = i + 1;
while (i < num_of_numbers && j < num_of_numbers) {
if (numbers[i] + numbers[j] == desired_sum) {
ans.push_back(make_pair(i + 1, j + 1));
i++;
j++;
break;
}
else if (numbers[i] + numbers[j] < desired_sum) {
j++;
}
else {
i++;
}
}
if (ans.size() >= 1) {
cout << ans[0].first << " " << ans[0].second << endl;
} else {
cout << "IMPOSSIBLE" << endl;
}
}
int main() {
solve_optimized();
}
Note: solve - for loop
solve_optimized - while loop
Please let me know. Thanks!