Advertisement
DeepRest

Can Place Flowers

Jan 18th, 2022 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. '''
  2. LOGIC:
  3. In between any two ones we need to fit max 01 pairs with 0 at last.
  4. (So 0101...01010 for odd gaps and 0101...010100 for even gaps ... Here gaps are bounded by 1)
  5. For eg
  6. 1 _ _ _ _ _ 1.    
  7. In these five gaps the last has to be zero and then we can fit 2 01 pairs    
  8. 1 _ _ _ _ 1
  9. Here also the last gap has to be zero and in the first three we can fit only one 01 pair(the third remains zero)
  10. So we conclude
  11. No of pairs = (gaps-1)//2 (minus one becoz last gap has to be zero)
  12. No. of new ones = no. of pairs
  13. To handle leading gaps prepend 10
  14. To handle trailing gaps append 01
  15. '''
  16. class Solution(object):
  17.     def canPlaceFlowers(self, flowerbed, n):
  18.         #flowerbed.append(0)
  19.         #flowerbed.append(1)
  20.         gaps = 1 #equivalent to prepending 10
  21.         res = 0
  22.         for i in flowerbed:
  23.             if i==1:
  24.                 res += (gaps-1)//2
  25.                 gaps = 0
  26.             else:
  27.                 gaps += 1
  28.         #equivalent to appending 01
  29.         return res+(gaps)//2 >= n
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement