Given an array of positive integers, how can I find the number of increasing (or decreasing) subsequences of length 3
? E.g. [1,6,3,7,5,2,9,4,8]
has 24
of these, such as [3,4,8]
and [6,7,9]
.
I've found solutions for length k
, but I believe those solutions can be made more efficient since we're only looking at k = 3
.
For example, a naive O(n^3)
solution can be made faster by looping over elements and counting how many elements to their left are less, and how many to their right are higher, then multiplying these two counts, and adding it to a sum. This is O(n^2)
, which obviously doesn't translate easily into k > 3
.
The solution can be by looping over elements, on every element you can count how many elements to their left and less be using segment tree algorithm which work in O(log(n))
, and by this way you can count how many elements to their right and higher, then multiplying these two counts, and adding it to the sum. This is O(n*log(n))
.
You can learn more about segment tree algorithm over here: Segment Tree Tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With