Cell fusion in Python


Suppose we have a list of numbers called cells; this list is representing sizes of different cells. Now, in each iteration, the two largest cells a and b interact according to these rules: So, If a = b, they both die. Otherwise, the two cells merge and their size becomes floor of ((a + b) / 3). We have to find the size of the last cell or return -1 if there's no cell is remaining.

So, if the input is like [20,40,40,30], then the output will be 16, in first iteration, 40 and 40 will die, then 20 and 30 become floor of ((20+30) / 3) = floor of 50/3 = 16

To solve this, we will follow these steps −

  • cells := convert each value of cells array negative

  • make a heap with cells

  • while cells is not empty, do −

    • delete two elements from cells and convert them negative again, and assign them as first and second consecutively

  • if first is not equal to second, then −

    • insert negative of floor of (first+second)/3) into heap

  • return negative of cells[0] if cells has some elements otherwise - 1

Let us see the following implementation to get better understanding −

Example

 Live Demo

from heapq import heapify, heappop, heappush
class Solution:
   def solve(self, cells):
      cells=[-x for x in cells]
      heapify(cells)
      while len(cells)>1:
         first,second = -heappop(cells), -heappop(cells)
         if first!=second:
            heappush(cells, -((first+second)//3))
      return -cells[0] if cells else -1
ob = Solution()
cells = [20,40,40,30]
print(ob.solve(cells))

Input

[20,40,40,30]

Output

16

Updated on: 02-Sep-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements