You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Problems/Data-structures/Day-09/sol/BEESA-MANISH/Solution2.cpp
+11-4Lines changed: 11 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -6,10 +6,17 @@ TC- o(n log n)
6
6
SC - o(n)
7
7
8
8
Approach:
9
-
Convert large numbers into smaller ranks so they are easy to work with.
10
-
Treat each element as the middle of a triplet.
11
-
Count bigger elements on the left and smaller elements on the right.
12
-
Multiply these counts and sum for all positions to get the answer.
9
+
Take each element as one by one and treat that element as middle element,count number of elements greater than that element on left side of that element and count
10
+
number of elements smaller than that element on right side of that element.
11
+
12
+
Use a Fenwick Tree (Binary Indexed Tree) to efficiently count elements in ranges, Since array values can be as large as 10^9, first compress the values to ranks 1..n
13
+
14
+
Do the left to right pass in Fenwick tree to count number of elements greater than current element on left side.
15
+
16
+
Reset Fenwick tree and do right to left pass to count number of elements smaller than current element on right side.
17
+
18
+
Finally, for each element multiply the two counts and sum them up to get the final answer.
0 commit comments