

My approach using sliding window
machines = [3,7,1,11,8]
k = 2
# machines = [3,9,4,2,16]
# k = 3
# machines = [3,2,6,1]
# k = 3
def calculateCost(machines,k):
n = len(machines)
leftSum = [0] * n
rightSum = [0] * n
# calculate cumulative connection cost from leftside
totalSum = 0
for i in range(1,n):
totalSum += abs(machines[i] - machines[i-1])
leftSum[i] = totalSum
# calculate cumulative connection cost from rightside
totalSum = 0
for i in range(n-2,-1,-1):
totalSum += abs(machines[i+1] - machines[i])
rightSum[i] = totalSum
#print(leftSum)
#print(rightSum)
l = 0
r = l + k - 1
res = math.inf
while(r+1<=n):
if(l == 0):
#window is begining,
currentCost = rightSum[r+1]
elif(r == (n-1)):
#window is at end
currentCost = leftSum[l-1]
else:
# calculate cost of edge after removing window
edgeCost = abs(machines[l-1] - machines[r+1])
currentCost = rightSum[r+1] + leftSum[l-1] + edgeCost
#print(l,r,currentCost)
res = min(res,currentCost)
l += 1
r += 1
return res
print(calculateCost(machines,k))Q2 -
same as q2 in https://leetcode.com/discuss/interview-question/1482144/amazon-online-assessment-september-2021/1095536
related to insertions and view operations
I followed heap approach which is also mentioned in comment, but got TLE on 5 test cases, passed for rest. I think we need balanced binary search tree to satisfy O(log(n)) search as O(N) search for view is still giving TLE in some cases.