Karat / VO 面试真题解析:Snowy Mountain Crossing

15次阅读
没有评论

You are planning a trek across a snowy mountain. On the mountain, it snows in the morning, the snow melts with the sun in the afternoon, and in the evening you can attempt a crossing.

Snow piles up at each location, making that location higher. If it has not snowed at a particular location for 2 days, the snow there starts melting on the afternoon of the second day, at a rate of one unit per day.

You can climb up and down one level while moving to the next position.

The player needs to cross the mountain with the least amount of climbing possible.

The crossing attempts are limited to the days in the forecast because the weather is unpredictable later.

Write a function that, given the base altitude of locations on the mountain and a list of snow forecasts for each day, calculates and returns the best day to perform the crossing as well as the number of climbs needed on that day.

For example, given the initial altitudes: [0, 1, 2, 1]

And the snow forecast for each morning:

[[1, 0, 1, 0],  # On day zero, one unit of snow will fall on positions 0 and 2.
[0, 0, 0, 0],  # On day one, it will not snow.
[1, 1, 0, 2]]  # On day two, two units of snow will fall on position 3, and one unit on positions 0 and 1.

This is the resulting mountain profile each evening, the player is represented by the letter P.

这道题要求你根据山体的初始高度和每天早晨的降雪预报,模拟每一天傍晚的山路状态,找出最适合穿越的一天,并返回当天需要的最少攀爬次数。核心是同时维护每个位置的高度变化:白天下雪会让高度增加,而若某个位置连续两天没有下雪,则从第二天下午开始按每天 1 的速度融雪。最终需要在每天的山体剖面上计算从起点到终点的穿越代价,通常会用数组状态模拟每一格高度,再结合路径代价评估来比较不同天数。

正文完
 0