File tree Expand file tree Collapse file tree
Problems/Mathematics/Day-02/sol/Sudhanshu Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+ typedef long long ll;
3+ typedef long double ld;
4+ using namespace std ;
5+
6+ int main ()
7+ {
8+ ios::sync_with_stdio (false );
9+ cin.tie (NULL );
10+
11+ int t;
12+ cin >> t;
13+ while (t--)
14+ {
15+ int n;
16+ cin >> n;
17+ vector<int > v (n);
18+
19+ for (int i = 0 ; i < n; i++)
20+ cin >> v[i];
21+
22+ sort (v.begin (), v.end ());
23+
24+ int low = v[0 ];
25+ int high = v[n - 1 ];
26+
27+ int adjust = (low == high) ? 2 : 1 ;
28+
29+ int cLow = 0 ;
30+ int cHigh = 0 ;
31+
32+ for (auto i : v)
33+ {
34+ if (i != low)
35+ break ;
36+ cLow++;
37+ }
38+ reverse (v.begin (), v.end ());
39+
40+ for (auto i : v)
41+ {
42+ if (i != high)
43+ break ;
44+ cHigh++;
45+ }
46+
47+ cout << cHigh * cLow * 2 / adjust << endl;
48+ }
49+
50+ return 0 ;
51+ }
52+
53+ /*
54+ APPROACH:
55+
56+ - Sort the array to easily identify minimum and maximum elements
57+ - Find the minimum (low) and maximum (high) values
58+ - Count occurrences of minimum value (cLow) and maximum value (cHigh)
59+ - If all elements are equal (low == high), we need to choose any 2 elements from n,
60+ so answer = n * (n-1) (dividing by 2 would give combinations, but we want pairs)
61+ - Otherwise, the answer is cLow * cHigh * 2 (considering both orderings of pairs)
62+
63+ TC: O(nlog n)
64+ SC: O(n)
65+ */
You can’t perform that action at this time.
0 commit comments