Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- LOGIC:
- In between any two ones we need to fit max 01 pairs with 0 at last.
- (So 0101...01010 for odd gaps and 0101...010100 for even gaps ... Here gaps are bounded by 1)
- For eg
- 1 _ _ _ _ _ 1.
- In these five gaps the last has to be zero and then we can fit 2 01 pairs
- 1 _ _ _ _ 1
- 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)
- So we conclude
- No of pairs = (gaps-1)//2 (minus one becoz last gap has to be zero)
- No. of new ones = no. of pairs
- To handle leading gaps prepend 10
- To handle trailing gaps append 01
- '''
- class Solution(object):
- def canPlaceFlowers(self, flowerbed, n):
- #flowerbed.append(0)
- #flowerbed.append(1)
- gaps = 1 #equivalent to prepending 10
- res = 0
- for i in flowerbed:
- if i==1:
- res += (gaps-1)//2
- gaps = 0
- else:
- gaps += 1
- #equivalent to appending 01
- return res+(gaps)//2 >= n
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement