I am trying to understand the algorithm that gives me the number of increasing subsequences of length K in an array in time O(nklog(n)). I know how to solve this very same problem using the O(k*n^2) algorithm. I have looked up and found out this solution uses BIT (Fenwick Tree) and DP. I have also found some code, but I have not been able to understand it.
Here are some links I've visited that have been helpful.
Here in SO
Topcoder forum
Random webpage
I would really appreciate if some can help me out understand this algorithm.
I am reproducing my algorithm from here, where its logic is explained:
You can optimize
*1*
and*2*
by using segment trees or binary indexed trees. These will be used to efficiently process the following operations on thenum
array:(x, v)
addv
tonum[x]
(relevant for*1*
);x
, find the sumnum[1] + num[2] + ... + num[x]
(relevant for*2*
).These are trivial problems for both data structures.
Note: This will have complexity
O(n*k*log S)
, whereS
is the upper bound on the values in your array. This may or may not be good enough. To make itO(n*k*log n)
, you need to normalize the values of your array prior to running the above algorithm. Normalization means converting all of your array values into values lower than or equal ton
. So this:Becomes:
This can be accomplished with a sort (keep the original indexes).