Buy and Sell Stock Once
Problem Statement
Write a program that takes an array of stock prices and return maximum profit that can be made by buying and selling one stock.
Problem Solving
- This question I have seen a hundred times, lets kill this once and for all.
- So a list of array with number and we are interested in the max profit.
- Max profit would be obtained by buying at a local minima followed by a local maxima.
- The brute force way would be for each day consider buying and then calculate how much profit we get by selling on remaining following days.
- This would surely give correct ans with quadratic time complexity.
- A linear approach would be to iterate through the array in ascending time and keep registering max_profit.
- At every element we check whether the element is a local minima if so the is it less than the current local minima, if yes then we update out buying option.
- Otherwise we continue iterating and registering max_profit.
- Stop when we reach the last element.
- Find code here.
Learning
- Like the previous problem problem solving really is emotionally challenging despite being able to solve the problem in decent time. The emotional strength to face it is enormous.
- Thinking the brute force way was obviously morale boosting that at least there is a way.
- Further optimizing it was easy and confidence boosting.
- I think I should now face problems with more confidence and these are really not that difficult.
- One more thing, today this problem was solved without any compiler errors and in one go.
No comments:
Post a Comment