Program to check robbers can rob the vault or not in Python

PythonServer Side ProgrammingProgramming

Suppose there are N number of robbers are trying to rob a vault. There was a guard but he went out for G amount of time, after that he will come back. And each robber has specific time to rob the vault, but at most two of them can enter into the vault at the same time. Now the problem is we have to check whether they can rob the vault of getting caught by the guard? We have to keep in mind that −

  • If one robber goes inside the vault at a time t and at the same time another robber comes out, then it is like they were never in the vault at the same time.

  • If the guard gets inside vault at time G and a robber comes out exactly at time G, the guard will not notice the robber.

So, if the input is like N = 3 G = 5 time = [3,5,2], then the output will be True, because possible arrangement is there, that is −

  • at time t=0, robber1 goes inside and comes out at t=3
  • at time t=0, robber2 goes inside and comes out at t=5
  • at time t=3, robber3 goes inside and comes out at t=5

To solve this, we will follow these steps −

  • if sum of all elements in time > 2*G, then
    • return False
  • otherwise when sum of all elements in time <= G, then
    • return True
  • otherwise,
    • valid := an array of size G + 1, and initially all values are False
    • valid[0] := True
    • for each x in time, do
      • for i in range G to 0, decrease by 1, do
        • if i-x >= 0 and valid[i-x], then
          • valid[i] := True
    • if sum of all elements in time - maximum of i for all i in range 0 to size of valid when valid[i] <= G, then
      • return True
    • otherwise,
      • return False

Example

Let us see the following implementation to get better understanding −

def solve(N, G, time):
   if sum(time) > 2*G:
      return False
   elif sum(time) <= G:
      return True
   else:
      valid = [False]*(G+1)
      valid[0] = True
      for x in time:
         for i in range(G,-1,-1):
            if i-x >= 0 and valid[i-x]:
               valid[i] = True
      if sum(time) - max(i for i in range(len(valid)) if valid[i]) <= G:
         return True
      else:
         return False

N = 3
G = 5
time = [3,5,2]
print(solve(N, G, time))

Input

3,5,[3,5,2]

Output

True
raja
Published on 23-Oct-2021 07:11:05

Advertisements