-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathappleStocks.js
39 lines (26 loc) · 1.48 KB
/
appleStocks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Writing programming interview questions hasn't made me rich yet ... so I might give up and start trading Apple stocks all day instead.
// First, I wanna know how much money I could have made yesterday if I'd been trading Apple stocks all day.
// So I grabbed Apple's stock prices from yesterday and put them in an array called stockPrices, where:
// The indices are the time (in minutes) past trade opening time, which was 9:30am local time.
// The values are the price (in US dollars) of one share of Apple stock at that time.
// So if the stock cost $500 at 10:30am, that means stockPrices[60] = 500.
// Write an efficient function that takes stockPrices and returns the best profit I could have made from one purchase and one sale of one share of Apple stock yesterday.
// For example:
// const stockPrices = [10, 7, 5, 8, 11, 9];
// getMaxProfit(stockPrices);
// // Returns 6 (buying for $5 and selling for $11)
// JavaScript
// No "shorting"—you need to buy before you can sell. Also, you can't buy and sell in the same time step—at least 1 minute has to pass.
const stockPrices = [10, 7, 5, 8, 11, 9];
function getMaxProfit(stockPrices) {
let profit = 0;
for (let i = 0; i < stockPrices.length; i++) {
for (let j = i+1; j < stockPrices.length; j++) {
let diff = stockPrices[j] - stockPrices[i]
if(diff>profit) profit = diff
}
}
return profit
}
console.log(getMaxProfit(stockPrices));
// Returns 6 (buying for $5 and selling for $11)