Skip to content

Instantly share code, notes, and snippets.

@axayjha
Last active May 16, 2025 14:23
Show Gist options
  • Save axayjha/4f57701681a2019a9ef481e0f2c0d084 to your computer and use it in GitHub Desktop.
Save axayjha/4f57701681a2019a9ef481e0f2c0d084 to your computer and use it in GitHub Desktop.
Sample
/**
* Given a list of daily stock prices, return the three stocks with the highest average price.
*
* @param {string[]} stocks - An array of strings, representing the stock names.
* @param {number[][]} prices - An array of arrays, where prices[i] is an array of daily prices for stocks[i].
* @returns {string[]} An array containing the names of up to three stocks with the highest average price,
* sorted by decreasing average value.
*/
function getTopStocks(stocks, prices) {
// Step 1: Calculate the average price for each stock and store it.
const stockDataWithAverages = [];
for (let i = 0; i < stocks.length; i++) {
const stockName = stocks[i];
const dailyPrices = prices[i];
let averagePrice = 0; // Default average if no prices are available or list is empty
if (dailyPrices && dailyPrices.length > 0) {
const sumOfPrices = dailyPrices.reduce((total, currentPrice) => total + currentPrice, 0);
averagePrice = sumOfPrices / dailyPrices.length;
}
stockDataWithAverages.push({
name: stockName,
average: averagePrice
});
}
// Step 2: Sort the stocks by their average price in descending order.
stockDataWithAverages.sort((stockA, stockB) => stockB.average - stockA.average);
// Step 3: Extract the names of the top three (or fewer, if not enough stocks).
const topStocks = stockDataWithAverages.slice(0, 3);
const topStockNames = topStocks.map(stock => stock.name);
return topStockNames;
}
// Example usage based on the problem description's structure:
// const exampleStocks = ["AMZN", "CACC", "EQIX", "GOOG", "ORLY", "ULTA"];
// const examplePrices = [
// [12.01, 11.09, 12.11, 10.93, 9.83, 8.14], // AMZN prices
// [10.34, 10.56, 10.14, 12.17], // CACC prices
// // ... (prices for EQIX, GOOG, ORLY, ULTA would follow)
// ];
// If GOOG, ORLY, AMZN have the top 3 averages in that order, the call:
// getTopStocks(exampleStocks, examplePrices) would return ["GOOG", "ORLY", "AMZN"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment