Grumpy Bookstore Owner in Python

PythonServer Side ProgrammingProgramming

Suppose a bookstore owner has a store open for number of customers list entries minutes. In every minute, some number of customers (customers[i]) enter the store, after that all those customers leave after the end of that minute. On some minutes, the owner is grumpy. Now if the owner is grumpy on the i-th minute, then grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are unhappy, otherwise they are happy. The bookstore owner knows a technique to keep themselves not grumpy for X minutes straight. That technique cannot be used more than once. We have to find the maximum number of customers that can be happy throughout the day. So if the input is like: customers = [1,0,1,2,1,1,7,5] and grumpy = [0,1,0,1,0,1] and X = 3, then the output will be 16. This is because the owner will not themselves grumpy for last three minutes. So the maximum number of happy customers are 1 + 1 + 1 + 1 + 7 + 5 = 16

To solve this, we will follow these steps −

  • set i := 0, j := 0, sums := empty list and temp := 0

  • while j – i + 1 < X

    • if grumpy[j] is 1, then temp := temp + customers[j]

    • increase j by 1

  • insert a list [temp, i, j] into sums array

  • increase i and j by 1

  • while j < length of customer list

    • if grumpy[i - 1] is 1, then temp := temp – customers[i - 1]

    • if grumpy[j] is 1, then temp := temp + customer[j]

    • insert a list [temp, i, j] into sums array

    • increase i and j by 1

  • sums := sort sums array based on the first element of the inner lists

  • index1 := second element of the last list in sums, index2 := third element of the last list in sums,

  • for i in range index1 to index2 set grumpy[i] := 0

  • ans := 0

  • for i in range 0 to length of customers

    • if grumpy[i] is 0, then ans := ans + customers[i]

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def maxSatisfied(self, customers, grumpy, X):
      i = 0
      j = 0
      sums = []
      temp = 0
      while j-i+1<X:
         if grumpy[j]:
            temp+=customers[j]
         j+=1
      sums.append([temp,i,j])
      i+=1
      j+=1
      while j<len(customers):
         if grumpy[i-1]:
            temp-=customers[i-1]
         if grumpy[j]:
            temp+=customers[j]
         sums.append([temp,i,j])
         i+=1
         j+=1
      sums =sorted(sums,key = lambda v : v[0])
      index1 = sums[-1][1]
      index2 = sums[-1][2]
      for i in range(index1,index2+1):
         grumpy[i] = 0
      ans = 0
      for i in range(len(customers)):
         if not grumpy[i]:
            ans+=customers[i]
      return ans
ob = Solution()
print(ob.maxSatisfied([1,0,1,2,1,1,7,5],[0,1,0,1,0,1,0,1],3))

Input

[1,0,1,2,1,1,7,5]
[0,1,0,1,0,1,0,1]
3

Output

16
raja
Updated on 02-May-2020 11:00:29

Advertisements