Given a vector of a sorted timestamps in microseconds, I need to determine the size of elements belonging to the same duration (say second).
My idea is to iterate over the vector until the last element belonging to the same duration, do this for each element and return the size of the biggest sub-vector.
Is there a smarter idea (with low time complexity) ?
I expect those posting comments are suggesting something like the following. This is Ruby code, but I readers who do not know Ruby can view it as pseudo code and should have no difficulty following it, particularly because I've displayed the results of intermediated calculations.
Suppose
A "current index" will always point to the first value in a group. In this example it will take on values
0(the first1),2(the first3),3(the first5),5(the first6),9(the first8) and11(the first9).The method
bsearch_indexperforms a binary search to return the index of the next higher value relative to a current index. If, for example, the current index is3(the first5),bsearch_indexwill return5(the first6). If there is no greater value than that at the current index (here when the current index is11, pointing at the first9),bsearch_indexreturnsniland there is an adjustment that can be seen in the code.The following is displayed.
The desired array,
[6, 6, 6, 6]can be easily constructed from the final value ofbest.A binary search works well when there are many instances of each value. On the other hand, if there are many different values and few instances of each it may be faster to simply enumerate the array, avoiding the overhead involved in performing a binary search.