Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of length 3 increasing (or decreasing) subsequences?

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.

like image 905
F5673 Avatar asked Aug 30 '25 16:08

F5673


1 Answers

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

like image 124
Humam Tlay Avatar answered Sep 07 '25 08:09

Humam Tlay