Program to check whether we can eat favorite candy on our favorite day in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of positive calues candiesCount where candiesCount[i] denotes the number of candies of the ith type we have. We also have another another array called queries where queries[i] has three parameters [favoriteType_i, favoriteDay_i, dailyCap_i]. We have some rules:

  • We start eating candies on day 0.

  • We cannot eat any candy of type i unless we have eaten all candies of previous i-1 types.

  • We must eat at least one candy per day until we have eaten all of them.

Maintaining these rules, we have to make an array of Boolean values for each query results and i-th entry is true if we can eat a candy of type favoriteType_i on day favoriteDay_i without eating more than dailyCap_i candies on any day. We can eat different types of candy on the same day, by following rule 2.

So, if the input is like candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,100]], then the output will be [true,false,true] because

  • If we eat 2 type-0 candies on day 0 and day 1, we will eat a type-0 candy on day

  • We can eat at most 4 candies each day. If we eat 4 candies every day, we will eat 4 type-0 candies on day 0 and 4 type-0, type-1 candies on day 1. Then on day 2, we can only eat 4 type-1, type-2 candies, so we cannot eat a candy of type 4 on day 2.

  • We can eat 1 candy each day, we will eat a candy of type-2 on day 13.

To solve this, we will follow these steps −

  • sumcandy := a list with a single element candiesCount[0]

  • index:= 1

  • while index < size of candiesCount, do

    • insert (sumcandy[index-1] + candiesCount[index]) at the end of sumcandy

    • index := index + 1

  • insert 0 at the end of sumcandy

  • res:= a new list

  • for each each in queries, do

    • typ:= each[0]

    • day:= each[1]

    • cap:= each[2]

    • if day+1 > sumcandy[typ] or (day+1)*cap <= sumcandy[typ-1], then

      • insert False at the end of res

    • otherwise,

      • insert True at the end of res

  • return res

Example

Let us see the following implementation to get better understanding −

def solve(candiesCount, queries):
   sumcandy = [candiesCount[0]]
   index=1
   while index < len(candiesCount):
      sumcandy.append(sumcandy[index-1] + candiesCount[index])
      index+=1
   sumcandy.append(0)
   res=[]
   for each in queries:
      typ=each[0]
      day=each[1]
      cap=each[2]
      if day+1 > sumcandy[typ] or (day+1)*cap <= sumcandy[typ-1]:
         res.append(False)
      else:
         res.append(True)
   return res

candiesCount = [7,4,5,3,8]
queries = [[0,2,2],[4,2,4],[2,13,100]]
print(solve(candiesCount, queries))

Input

[7,4,5,3,8], [[0,2,2],[4,2,4],[2,13,100]]

Output

[True, False, True]
raja
Updated on 06-Oct-2021 08:06:51

Advertisements