LinkedIn 面试题|分享国际站面经(LinkedIn | Senior SDE | Phone| min distance for elevator)
1735
发布于 未知归属地

感觉这边分享面试题的有点少,把我在国际站做过的题分享过来

Given two arrays representing an elevator problem, one array represents the weight of each person, and the second one represents the floor they are looking to reach.
For example:
[60, 20, 80, 180, 60]
and
[2, 2, 3, 3, 5]
The maximum weight the elevator can carry is 200.
Question: what's the least amount of distance the elevator has to travel? (From floor 1 to floor 2, distance will be 2-1=1)
Assume everyone starts on the first floor, and the elevator has to come back to the first floor to p ick up every group.
Assume people cannot skip the line. ie. 60 and 20 have to go before 80.
This part is relatively simple. Because I can't skip the line, just do a linear scan.
Follow up is much more difficult: what if people can skip the line? I wasn't sure how to solve it. Maybe with backtracking or DP?

这个题没想到什么好办法,回溯暴力解了,抛砖引玉

weight = [60, 20, 80, 180, 60]
level = [2,2,3,3,5]
weight, level = map(list, zip(*sorted(zip(weight, level))))
vis = [False] * len(weight)
target = 200

dis = 0
minDis = float("inf")

# maxH is max height of current group
# curr is sum weight of current group
# dis is total distance of current division
# k is remaning people
def backtrack(start, maxH, curr, dis, k):
    global minDis
    if k == 0:
        minDis = min(minDis, dis + (maxH - 1)*2)
        return

    for i in range(start, len(weight)):
        if vis[i]: continue
        if curr + weight[i] > target:
            backtrack(0, 0, 0, dis + (maxH - 1) * 2, k)
            break
        vis[i] = True
        backtrack(i+1, max(maxH, level[i]), curr + weight[i], dis, k - 1)
        vis[i] = False
        

backtrack(0, 0, 0, 0, 5)
print(minDis)
评论 (0)