Cresta OA 面试题解析:返回平均价格最高的三只股票

13次阅读
没有评论

Objective

Given a list of daily stock prices, return the three stocks with the highest average price.

Implementation

Implement the function get_top_stocks(stocks, prices), which takes as input:

  • a list of strings stocks, representing the considered stocks
  • a 2-dimensional list prices, representing the stock prices for each day

Your get_top_stocks function should return a list containing the names of the three stocks with the highest average value. The list should be sorted by decreasing average price.

Example

stocks = ["AMZN", "CACC", "EQIX", "GOOG", "ORLY", "ULTA"]
prices = [[12.81, 11.09, 12.11, 10.93, 9.83, 8.14],
    [10.34, 10.56, 10.14, 12.17, 9.99, 9.34],
    [11.99, 12.84, 12.56, 10.99, 10.21, 11.02]
]

The function should return the three stocks with the highest average price, sorted by decreasing average value.

这道题要求根据每天的股票价格,计算每只股票在所有天数中的平均值,然后按平均价格从高到低选出前 3 名。核心做法是把每只股票的价格按列聚合,计算总和再除以天数,最后对股票与平均值组成的列表进行排序并取前三个。因为股票数量不大,直接遍历所有价格即可,时间复杂度为 O(股票数 × 天数),实现简单且稳定。

正文完
 0