Check Your Stock Gains

Difficulty: Hard

The challenge for last month’s Exercise was to generate a table showing a stock price updated every 30 minutes during the trading day. This month’s Exercise expands upon the process by having your code examine the stock price highs and lows and determine the greatest increase in stock value. This calculation means more than just finding the high and low values.

To review, here is the output from the earlier Exercise:

 9:00 Price $8/share
 9:30 Price $9/share
10:00 Price $7/share
10:30 Price $6/share
11:00 Price $8/share
11:30 Price $10/share
12:00 Price $12/share
12:30 Price $11/share
 1:00 Price $10/share
 1:30 Price $13/share
 2:00 Price $11/share
 2:30 Price $5/share
 3:00 Price $8/share
 3:30 Price $9/share
 4:00 Price $11/share

In Figure 1, I’ve charted the stock price over time so that you can see its change in value. The low of the day is $5/share at 2:30; the high is $13/share at 1:30. The market may not be this volatile in real life, still the point is to determine the greatest gain in stock value. The range from $5 to $13 is $8, but this range moves back in time, so it’s invalid.

Figure 1. Stock price throughout the day.

Your task for this month’s Exercise is to write code that determines the largest gain in value moving forward in time (not the difference between the day’s high and low values).

Your code must examine all price rises throughout the day to determine which is greatest. It doesn’t matter if the price rises, dips, and then rises again. The goal is to determine (through hindsight of course) what would have been the best time to buy and sell for the greatest gain through the day?

You need only output the time stamp and stock price for the greatest gain, time to buy and then time to sell. You need not output the entire table as was done in last month’s Exercise.

Obviously, this Exercise raises the difficulty level. I can imagine several ways to solve the puzzle, each one fairly involved. It took me some thought and planning to get the results correct. I hope you’re up to the challenge!

Please try this Exercise on your own before you check out my solution.

Leave a Reply