Cresta OA Interview Question: Return the Three Stocks with the Highest Average Price

11 Views
No Comments

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.

This problem asks you to compute the average price of each stock across all days, rank the stocks by that average, and return the top three. A straightforward solution is to scan prices column by column, accumulate each stock’s total, divide by the number of days, then sort the stocks by average price in descending order and take the first three. The constraints are small enough that a simple O(stocks × days) approach is more than sufficient.

END
 0