File tree Expand file tree Collapse file tree
Problems/Mathematics/Day-02/sol/Mukut Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ Problem: counting pairs where absolute difference equals max possible difference in array
3+
4+ My approach:
5+ basically max diff is always gonna be max_element - min_element
6+ so we just need pairs where one is max and other is min
7+ first find both values then count how many times each appears
8+ if everything is same number then answer is just n*(n-1) (all pairs work)
9+ otherwise its 2*count_max*count_min (since both (i,j) and (j,i) count as different)
10+
11+ TimeComplexity: O(n)
12+ SpaceC: O(n)
13+
14+ CodeForces submission: https://codeforces.com/contest/1771/submission/355388765
15+ */
16+
17+ #include < bits/stdc++.h>
18+ using namespace std ;
19+
20+ int main (){
21+ int t;
22+ cin >> t;
23+
24+ while (t--){
25+ int n;
26+ cin >> n;
27+ vector<int > arr (n);
28+
29+ for (int i=0 ; i<n; i++){
30+ cin >> arr[i];
31+ }
32+ int maxi = arr[0 ], mini = arr[0 ];
33+ for (int i=1 ; i<n; i++){
34+ if (arr[i] > maxi) maxi = arr[i];
35+ if (arr[i] < mini) mini = arr[i];
36+ }
37+ if (maxi == mini){
38+ long long result = (long long )n * (n-1 );
39+ cout << result << endl;
40+ continue ;
41+ }
42+ long long max_count = 0 , min_count = 0 ;
43+ for (int i=0 ; i<n; i++){
44+ if (arr[i] == maxi) max_count++;
45+ if (arr[i] == mini) min_count++;
46+ }
47+ long long answer = 2 * max_count * min_count;
48+ cout << answer << endl;
49+ }
50+
51+ return 0 ;
52+ }
You can’t perform that action at this time.
0 commit comments