35
3
Stock Time Machine
You've gained access to a dataset, tomorrowStocks
, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.
// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
Output
Your task is to determine the best possible outcome of 1 purchase
and 1 sale
of 1 stock
from the given dataset.
Gotchas
- You must buy and sell exactly 1 stock.
- You may not buy and sell in the same time slot.
- You must buy before you sell.
Test Data
[1,2,3,4,5] # 4
[1,99,2,105] # 104
[99,1,99,100] # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1] # 0
[5,4,3,1] # -1
[5,2,1] # -1
[5,4,1] # -1
[55,45,20,1] # -10
[5,1] # -4
[10,7,5,1] # -2
[7] # Invalid input -- assume size >= 2
This is a code-golf; submit the shortest answer in your favorite language!
11Welcome to PPCG, nice first question! :) – FryAmTheEggman – 2016-07-15T19:12:13.497
Can we assume the output is deterministic (i.e. There is always one solution that is definitively the best, and no ties) – MayorMonty – 2016-07-15T19:49:23.243
@SpeedyNinja -- Not sure I understand, but I'm leaning towards no under the assumption that you're asking if you can ignore inputs like
[5,5,5,5,3,3]
. – MrDuk – 2016-07-15T19:51:51.7171Too bad the interpreter for a language I'm building isn't finished yet, as it should be able to solve this in 4 bytes... I need to finish that asap so I can't miss out on so many good questions! – Steven H. – 2016-07-15T22:08:35.693
@MrDuk I can imagine a situation where there are two equally valuable solutions to a sequence, can we assume that such a situation will never happen? – MayorMonty – 2016-07-16T00:41:12.437
1@SpeedyNinja This is actually in the test cases. In test case
[5,4,3,1]
you can either but for5
and sell for4
or buy for4
and sell for3
to get the optimal result of-1
. – Martin Ender – 2016-07-16T11:20:35.6431@Fawful You could add your answer as non-competing later. I would definetly be interested in seeing it – CocoaBean – 2016-07-16T23:12:48.967
@CocoaBean, I'll let you know once I have it working. I also realized that I could golf off an additional byte, so when everything is functional the solution should be 3 bytes. – Steven H. – 2016-07-17T02:36:07.780