AP Worksheet 2 - Alasso
AP Worksheet 2 - Alasso
Brute Force Approach:We can start from each index and check whether we are able to
complete the loop. If not we start again from the next index. We keep on doing this till we get the
first index from which we start and are able to complete the whoole loop.
CODE:
# Harshit Singh Bisht
# 21 BCS 5431
def solve(petrol,distance,n):
start,tank=0,0
for i in range(n): #Start from each index
start=i
tank=0 #Reset the tank for each iteration
for j in range(n):
current=(start+j)%n #To make the index in range fo
r circular array
tank+=petrol[current]-
distance[current] #Add the petrol and subtract the petrol required
to reach next station
if tank<0: #If petrol in tank becomes negative, we ca
nnot complete the loop
break
if j==n-
1: #If we visit all n pumps, task is completed
return start
n=int(input())
petrol,distance=[],[]
for i in range(n):
p,d=[int(x) for x in input().split()]
petrol.append(p),distance.append(d)
print(solve(petrol,distance,n))
OUTPUT:
ans = 0
a = [0]+a
b = [0]+b
for i in range(len(a)):
for j in range(len(b)):
sa = sum(a[:i+1])
sb = sum(b[:j+1])
if sa+sb > x:
break
ans = max(ans, i+j)
return ans
def solve(a,b):
total = 0
i = len(a)
ans = i
j = 1
for i in range(len(a)):
total += a[i]
if total > x:
ans = i
break
ans_total = x + 1
total = sum(a[:i])
while (total <= x and i > 0) or j < len(b):
if total < x:
total += b[j - 1]
j += 1
elif total > x:
total -= a[i - 1]
i -= 1
else:
total -= a[i - 1]
i -= 1
total += b[j - 1]
j += 1
for _ in range(int(input())):
n, m, x = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
_sum_a, _sum_b = sum(a), sum(b)
if _sum_a + _sum_b <= x:
print(n+m)
elif n <= 200 and m <= 200:
print(brute(a,b))
else:
ans = solve(a,b) if _sum_a < _sum_b else solve(b,a)
print(ans)
OUTPUT:
COMPLEXITY:
The time complexity for the QUEUE is O(N2).
The time complexity for the STACK is O(1), except for the search operation which has a time
complexity of O(n).