My apologies, I know this type of question already has an answer over here but I couldn't figure out how to use it for my code. I wrote a program for a problem-solving contest that accepts an array and tries to maximize the value of |Ax−Ay|+|Ay−Az|+|Az−Ax| over all triples of pairwise distinct valid indices (x,y,z). The program has the following constraints:
- 1≤t≤5
- 3≤n≤10^5
- |Ai|≤10^9 for each valid i
I am getting the following error when I try to run it - "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc". All I could figure out from the answered questions was that my code encounters memory allocation problem but I couldn't find where and when it does that? Maybe when it deals with large values? What is causing the error?
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<ll> vll;
typedef vector<int> vi;
#define rep(i, a, b) for (ll i = a; i < b; i++)
#define repi(i, a, b) for (ll i = a; i <= b; i++)
#define repn(i, a, b) for (ll i = a; i >= b; i--)
#define fast() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
// solve() function
void solve()
{
ll n;
cin >> n;
vll v(n);
rep(i, 0, n)
cin >>
v[i];
sort(all(v));
ll x = v[0], y = v[1], z = v[n - 1];
ll ans = abs(x - y) + abs(y - z) + abs(z - x);
cout << ans << endl;
}
// driver function
int main()
{
fast();
ll t = 1;
cin >> t;
rep(i, 0, t)
{
solve();
}
return 0;
}
The input format is as follows:
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1, A2,…,AN.
The following is a sample input:
3
3
2 7 5
3
3 3 3
5
2 2 2 2 5