Stock Market Max Profit
For this week I did a problem called maxProfit. I found that this problem was actually a bit more practical for real life. The problem is that you are given a list containing integers that represent the price of a stock at a certain day. For example a list of [4,3,2,6,8,1,18,3,5,7]. For example at index 0 the stock was at 4 dollars and index 1 the price was 3 dollars. We would want to buy the stock at the lowest price possible and sell the stock at the highest price possible. For example in this case we would want to buy at price 1 and sell at price 18. We take the difference of that and our profit would be 17.
At first I thought right away of going to a double for loop and taking the difference at every step and seeing if that was the max profit. I however have been reading about big o(N) notation and that would not be optimal. That would be O(N^2). I thought about a faster solution where would would just go through the list once and have a O(N) time. The way we accomplish this is by using 2 pointers. One to keep track of the buy and one to keep track of the sale. We will call our buy pointer 'left' and we will call our sell pointer 'right'. We will also keep a variable called max profit that will keep track of our current max profit. We will iteration through our list as long as our right pointer is less than the length of the list.
We first initialize 2 variable for buy and sell using our pointers. If the current buy is less than the sell then we will calculate the difference. We create a temporary variable and compare that to the max profit. If it is greater than our max profit then we will update our max profit. If buy is greater than sell we will update make our left pointer = right pointer. At first I thought about increment by 1. However if we do this we would not get the right answer. That is because if buy is greater than sell at that point there was not any other buy point that was cheaper than the current so incrementing by one would not be optimal and we would get the wrong answer. Our right pointer however will always increment by one regardless. At the end we just return the max profit to the user.
I find this interesting. Very applicable in real life and once the code is computed, you do not need algebra or calculus to compute the max profit every single time.
ReplyDeleteVery nice work this week, Sergio.
ReplyDelete