Блог пользователя anucode

Автор anucode, история, 2 недели назад, По-английски

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) ?

  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
2 недели назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
Code
»
2 недели назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

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
»
2 недели назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится
Code
Algorithm
»
2 недели назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
submission