Skip to content

Commit 2fbb5a2

Browse files
authored
Merge pull request #202 from DeadlySatwik/issue4
Added solution to Day-02 q001
2 parents 495a95b + 8facdea commit 2fbb5a2

1 file changed

Lines changed: 100 additions & 0 deletions

File tree

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
/*
2+
Problem Statement:
3+
Hossam and Hazem want to count the number of interesting pairs (i, j) such that:
4+
1. 1 <= i, j <= n
5+
2. i != j
6+
3. |a[i] - a[j]| == max(|a[p] - a[q]|) for all 1 <= p, q <= n.
7+
8+
---------------------------------------
9+
Approach:
10+
1. Find the maximum and minimum values in the array. Let them be maxi and mini.
11+
2. The maximum absolute difference is diff = maxi - mini.
12+
3. We need to find pairs (a[i], a[j]) such that |a[i] - a[j]| = diff.
13+
4. Case 1: If maxi == mini (all elements are same), then any pair (i, j) with i != j works.
14+
The count is n * (n - 1).
15+
5. Case 2: If maxi != mini, we need one element to be maxi and the other to be mini.
16+
Count the occurrences of maxi (cntmax) and mini (cntmin).
17+
The number of pairs is 2 * cntmin * cntmax (since order matters.
18+
19+
----------------------------------------
20+
Time Complexity: O(n) - find min, max and their counts.
21+
Space Complexity: O(n) - store the input array.
22+
23+
----------------------------------------
24+
Example:
25+
Input:
26+
5
27+
6 2 3 8 1
28+
29+
Process:
30+
1. mini = 1, maxi = 8.
31+
2. diff = 7.
32+
3. cntmin (1) = 1.
33+
4. cntmax (8) = 1.
34+
5. Result = 2 * 1 * 1 = 2.
35+
36+
Output:
37+
2
38+
*/
39+
40+
#include <bits/stdc++.h>
41+
using namespace std;
42+
#define ll long long
43+
#define vll vector<ll>
44+
#define out(x) cout << (x) << endl
45+
#define outr(x) \
46+
{ \
47+
cout << x << endl; \
48+
return; \
49+
}
50+
51+
void solve()
52+
{
53+
ll n;
54+
cin >> n;
55+
vll a(n);
56+
int mini = INT_MAX;
57+
int maxi = INT_MIN;
58+
59+
for (int i = 0; i < n; i++)
60+
{
61+
cin >> a[i];
62+
if (a[i] < mini)
63+
mini = a[i];
64+
if (a[i] > maxi)
65+
maxi = a[i];
66+
}
67+
68+
if (mini == maxi)
69+
{
70+
cout << n * (n - 1) << endl;
71+
return;
72+
}
73+
74+
ll cntmin = 0;
75+
ll cntmax = 0;
76+
for (int x : a)
77+
{
78+
if (x == mini)
79+
cntmin++;
80+
if (x == maxi)
81+
cntmax++;
82+
}
83+
84+
cout << 2*cntmin*cntmax << endl;
85+
}
86+
87+
int main()
88+
{
89+
ios_base::sync_with_stdio(false);
90+
cin.tie(NULL);
91+
int t;
92+
cin >> t;
93+
while (t--)
94+
{
95+
solve();
96+
}
97+
return 0;
98+
}
99+
100+
//submission link: https://codeforces.com/problemset/submission/1771/355269691

0 commit comments

Comments
 (0)