This is only possible if you have sorted the array. In this case, a binary search for the smallest value conveys your condition and calculates the score simply by dividing your range of indices by the found position into two intervals. Then just calculate the length of the interval that conveys your condition.
If the array is not sorted, and you need to keep its order, you can use index sorting. When combining:
Definition
Let <i0,i1> be your used range of indices and x be your value.
index sorting array <i0,i1>
so create an array of size m=i1-i0+1 and index its sorting. This task is O(m.log(m)) , where m<=n .
binary search x position in an array of indices
This task is O(log(m)) and you need an index j = <0,m) for which array[index[j]]<=x is the smallest value <=x
count the amount
Just count the number of indices after j to m
count = mj;
As you can see if the array is sorted, you got O(log(m)) complexity, but if it is not, you need to sort O(m.log(m)) , which is worse than the naive O(m) approach that follows use only if the array changes frequently and cannot be sorted directly.
[Edit1] What do I mean by index sorting
By type of indexes, I mean the following: let it have an array a
a[] = { 4,6,2,9,6,3,5,1 }
Sorting an index means that you create a new array of ix indices in sorted order, for example, by increasing the sorting of the index:
a[ix[i]]<=a[ix[i+1]]
In our example, sorting the index bubbles looks something like this:
Thus, the result of index sorting increases as follows:
The original array remains unchanged, only the index array changes. Elements a[ix[i]] , where i=0,1,2,3... are sorted in ascending order.
So now, if x=4 on this interval, you need to find (search in the bean) which i has the smallest, but still a[ix[i]]>=x like this:
So answer 5 : >=4
[Edit2] Just to be sure you know what binary search means for this
i=0;
so you need the index i and the binary bitmask j (degree 2). First, set i with zero and j , and the greatest power 2 is even less than n (or in this case m ). Fro try on something like this:
i=0; for (j=1;j<=m;j<<=1;); j>>=1;
Now in each iteration test, if a[ix[i+j]] , the search condition is sufficient or not. If so, update i+=j otherwise leave it as is. After that, go to the next bit so j>>=1 , and if j==0 stop still repeat the iteration. at the end, you find the value a[ix[i]] , and index i in log2(m) iterations, which are also the number of bits needed to represent m-1 .
In the above example, I use the condition a[ix[i]]<4 , so the value found was the largest number <4 in the array. since we also needed to include 4 , then I just increment the index once at the end (I could use <=4 , but was too lazy to rewrite all this again).
The number of such elements is simply the number of elements in the array (or interval) minus i .