Unicorns / VO 面试真题解析:Area Under a Piecewise Line Graph|前缀和、数学、折线面积

20次阅读
没有评论

You are given a graph with X and Y axes. Each axis represents positive integers.

We will plot a graph based on given X and Y points.

Starting from (0,0), X will increment by 1 on the X axis.

The Y axis will represent the following format:

  • If X is 0, Y is 0. (0,0)
  • If X is 1, Y is 1. (1,1)
  • If X is 2 or more, the X-th Y is (X-1-th Y + X-2-th Y)

For example, if X = 2, Y = (0 + 1) = 1.

Given a series of (X, Y) points, a line will be drawn.

See the example image for visualization.

Write a function that takes input value X, and calculate the area underneath the drawn lines.

这道题本质上是在考察斐波那契式递推序列对应的折线面积计算:先根据题目规则生成每个点的坐标,再把相邻点连成折线,最终要求的是曲线下方的面积。由于图形是由连续线段组成,面积可以分段处理,常见做法是结合前缀和或逐段梯形面积公式来累加;如果题目输入范围较大,则需要注意用线性时间完成坐标生成和面积统计,避免重复计算。

正文完
 0