Advertisement
akashtadwai

Arrange-II

Aug 15th, 2021
1,438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. import functools
  2. class Solution:
  3.     # @param A : string
  4.     # @param B : integer
  5.     # @return an integer
  6.     @functools.lru_cache(None)
  7.     def dfs(self,i,d,A) :
  8.         n=len(A)
  9.         if d==1:
  10.             w,b=0,0
  11.             for idx in range(i,n):
  12.                 w+=A[idx]=='W'
  13.             b = n-i-w
  14.             return w*b
  15.        
  16.         res,w,b= float('inf'), 0,0
  17.         for j in range(i,n):
  18.             w+=A[j]=='W'
  19.             b+=A[j]=='B'
  20.             res = min(res,w*b+self.dfs(j+1,d-1,A))
  21.         return res
  22.            
  23.     def arrange(self, A, B):
  24.         n = len(A)
  25.         if n < B:
  26.             return -1
  27.         return self.dfs(0,B,A)
  28.            
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement