anucode's blog

By anucode, history, 7 months ago, In English

We have an array of integer and we want at evey odd index i we have to find sum of first i/2 smallest number from index 1 to index i

lets

At index 1 sum of 0 smallest number

At index 3 sum of first one smallest number

At index 5 sum of first two smallest number

At index 7 sum of first three smallest number

At index 9 sum of first four smallest number

and so on.

any solution/Idea in o(n) or o(nLogn) ?

  • Vote: I like it
  • +5
  • Vote: I do not like it

»
7 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it
Code
»
7 months ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

This can be solved without any special data structure. Assume $$$0$$$ based indexing. At index $$$i$$$ you want $$$\lfloor \frac{i}{2} \rfloor$$$ smallest numbers.

You can maintain two multisets $$$\texttt{S}$$$ and $$$\texttt{B}$$$. In $$$\texttt{S}$$$ we will be store smaller numbers while in $$$\texttt{B}$$$ we will store the bigger elements More formally, minimum element of $$$\texttt{B}$$$ should be greater than equal to maximum element of $$$\texttt{S}$$$.

If you notice carefully then you will see that we want to keep lengths of $$$\texttt{S}$$$ and $$$\texttt{B}$$$ as close as possible with $$$\texttt{B}$$$ having bigger size than $$$\texttt{S}$$$ if you cannot keep the sizes equal. At each step you can decide whether you want to put element in $$$\texttt{S}$$$ or $$$\texttt{B}$$$ by first filling the multiset with smaller size and then until you find $$$\textbf{Maximum element of}$$$ $$$\texttt{S}$$$ > $$$\textbf{Minimum element of}$$$ $$$\texttt{B}$$$. You can keep track of the sum of elements present in $$$\texttt{S}$$$ easily.

Code Snippet
»
7 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it
Code
Algorithm
»
7 months ago, # |
  Vote: I like it 0 Vote: I do not like it
submission