// Suppose we could access yesterday's stock prices as an array, where: // The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time. // So if the stock cost $500 at 10:30am, stockPricesYesterday[60] = 500. // Write an efficient function that takes stockPricesYesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. // The expected format is: // 6 (buying for $5 and selling for $11)
// Suppose we could access yesterday's stock prices as an array, where:
// The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time.
// So if the stock cost $500 at 10:30am, stockPricesYesterday[60] = 500.
// Write an efficient function that takes stockPricesYesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.
// The expected format is:
// 6 (buying for $5 and selling for $11)
function utcTime(date) {
try {
if (date instanceof Date) {
var utc = date.getTime() - (date.getTimezoneOffset() * 60000);
date.setTime(utc);
return date;
} else {
throw new Error('"date" is not an instance of Date');
}
} catch (error) {
console.error(error);
}
}
function getOpeningDateTime(date) {
try {
if (date instanceof Date) {
date.setHours(9,30,0,0);
return utcTime(date);
} else {
throw new Error('"date" is not an instance of Date');
}
} catch (error) {
console.error(error);
}
}
function getDateYesterday() {
let yesterday = new Date(Date.now() - 86400000);
return yesterday;
}
function removeIndex(indexToRemove, arr) {
return arr.filter(function(price, index) {
return indexToRemove !== index
});
}
function getMinPrice(stockPricesYesterday) {
return stockPricesYesterday.reduce(function(a, b) {
return Math.min(a, b);
});
}
function getMaxPrice(stockPricesYesterday) {
return stockPricesYesterday.reduce(function(a, b) {
return Math.max(a, b);
});
}
function getMaxProfit(stockPricesYesterday) {
if (stockPricesYesterday.length === 0) return;
const yesterday = getDateYesterday();
const openingDateTime = getOpeningDateTime(yesterday);
const minPrice = getMinPrice(stockPricesYesterday);
const maxPrice = getMaxPrice(stockPricesYesterday);
const minPriceIndex = stockPricesYesterday.indexOf(minPrice);
const maxPriceIndex = stockPricesYesterday.indexOf(maxPrice);
if (maxPriceIndex < minPriceIndex) {
const newStockPricesYesterday = removeIndex(minPriceIndex, stockPricesYesterday);
return getMaxProfit(newStockPricesYesterday);
}
const profit = maxPrice - minPrice;
return `${profit} (buying for $${minPrice} and selling for $${maxPrice})`;
}
var stockPricesYesterday = [10, 7, 5, 8, 11, 9, 2];
console.log(getMaxProfit(stockPricesYesterday));
// returns 6 (buying for $5 and selling for $11)