File tree Expand file tree Collapse file tree
Problems/Mathematics/Day-02/sol/Lavay Garg Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /* ## Problem Description
2+
3+ Hossam woke up bored, so he decided to create an interesting array with his friend Hazem.
4+
5+ You are given an array of `n` positive integers
6+ `a1, a2, ..., an`.
7+
8+ Hossam will choose a number `ai` and Hazem will choose a number `aj`.
9+
10+ Your task is to count the number of index pairs `(i, j)` such that:
11+
12+ - `1 ≤ i, j ≤ n`
13+ - `i ≠ j`
14+ - The absolute difference `|ai − aj|` is equal to the **maximum absolute difference** over all pairs in the array
15+
16+ ---
17+
18+ ## Input Format
19+
20+ - The first line contains a single integer `t` — the number of test cases.
21+ - For each test case:
22+ - The first line contains an integer `n`
23+ - The second line contains `n` integers `a1, a2, ..., an`
24+
25+ ---
26+
27+ ## Output Format
28+
29+ - For each test case, print a single integer — the number of valid pairs `(i, j)`.
30+
31+ ---
32+
33+ ## Constraints
34+
35+ - `1 ≤ t ≤ 100`
36+ - `2 ≤ n ≤ 100000`
37+ - `1 ≤ ai ≤ 100000`
38+ - The sum of `n` over all test cases does not exceed `100000`
39+
40+ ---*/
41+ #include < bits/stdc++.h>
42+ using namespace std ;
43+ int main (){
44+ int t;
45+ cin>>t;
46+ while (t--){
47+ int n;
48+ cin>>n;
49+ long long a[n];
50+ for (int i=0 ;i<n;i++){
51+ cin>>a[i];
52+ }
53+ sort (a,a+n);
54+ if (a[0 ] == a[n - 1 ]) {
55+ cout << 1LL *n*(n-1 )<< " \n " ;
56+ continue ;
57+ }
58+ long long maxdiff=a[n-1 ]-a[0 ];
59+ long long min=0 ;
60+ long long max=0 ;
61+ for (int i=0 ;i<n;i++){
62+ if (a[i]==a[0 ]){
63+ min++;
64+ }
65+ if (a[i]==a[n-1 ]){
66+ max++;
67+ }
68+
69+ }
70+ cout<<2LL *max*min<<endl;
71+ }
72+ }
73+ // Time Complexity=O(t*nlogn+t*n)
74+ // space complexity=O(n)
You can’t perform that action at this time.
0 commit comments