Finding the maximum drop in the stock price[reviewed]


Problem

You are given the array of integers, each of which represents the stock price of each day. You need to find the maximum drop in the stock price and buying and selling date, such that input[x] > input[y], where  x > y 

For example, given stock prices {2,4,-1,5, 7,6, 1}, the maximum drop should be 8, and [2, 4] will be an answer because the drop from -1 to 7 is 8, and the biggest increase. If the stock is bout when its price is at -1 and sells it when its price is at 7 the gain will be 8.

This question is sometimes stated a little differently like " given the series of stock prices, find the day you can make the most profit". Either way, the principle is the same. 

Basically, you need to iterate over the array, while remembering two facts:

1) Position of maximum value
As we progress through the array, we first need to start from the 1st integer as the maximum number. However, we should change the position if we encounter a smaller value to increase the chance of a bigger drop.

2) Maximum difference value

Each time we perform the subtraction input[max_value] from input[cur_pos], we remember the maximum difference value.

Here is the complete code running in O( N ), where N is the number of integers in the array.


Practice statistics
1:36: to think up the algorithm
7:19: to write up the code.

UPDATE(2019-07-26): solved the problem again. I could not understand the problem and later found that the question was incorrect.

I fixed the question and my explanation.  After fixing the question, wrote the solution in python.
Here is a solution in python.


Practice statistics:
10:00: couldn't come up with an algorithm satisfying the question.
10:00: after fixing the question, finished writing the code (one bug in the test code).


UPDATE(2022-06-10): solved the problem again. Took a while to understand the problem and come up with the most efficient O( N ) algorithm.

24:00 to come up with the algorithm with O( N ^2) running time
22:00 to fix the mistakes and revise the first code for O (N) running time

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots