title: Find the minimum number of steps to half the sum of elements in a list where each step halves an item in the list in O(N)
body: <p>I came across an interview question that went like this:</p>
  <blockquote>
  <p>There are factories in an area which produce a pollutive gas and filters are to be installed at each factory to reduce the pollution. Each filter installed would half the pollution in that factory. Each factory can have multiple filters. There is a list of N integers representing the level of pollution in each of the N factories in the area. Find the minimum number of filters needed to half the overall pollution.</p>
  <p>E.g. - Let [3, 5, 6, 1, 18] be the list of pollution levels in 5 factories</p>
  <ul>
  <li><p>Overall pollution = 3+5+6+1+18 = 33 (target is 33/2 = 16.5)</p>
  </li>
  <li><p>Install a filter in factory given by index=4 -- &gt; pollution levels will be [3, 5, 6, 1, 9]</p>
  </li>
  <li><p>Install a filter in factory given by index=4 -- &gt; pollution levels will be [3, 5, 6, 1, 4.5]</p>
  </li>
  <li><p>Install a filter in factory given by index=2 -- &gt; pollution levels will be [3, 5, 3, 1, 4.5]</p>
  </li>
  <li><p>Need 3 filters minimum to half the overall pollution.</p>
  </li>
  </ul>
  <p>N is an integer within the range [1....30,000]. Each element in the list is an integer within the range [0....70,000]</p>
  </blockquote>
  <p>The solution I came up with for this was simple:
  Find the max in the list and half in every time until the sum is &lt;=target</p>
  <pre><code>def solution(A):
      total = sum(A)
      target = total/2
      count = 0
      while total&gt;target:
          count+=1
          max_p = max(A)
          total-= max_p/2
          A.remove(max_p)
          A.append(max_p/2)
      return count
  </code></pre>
  <p>This works well, except that the time complexity seems to be O(N^2). Can someone please suggest an approach to solve this with less time complexity (preferably O(N))?</p>