5.Best Time to Buy and Sell Stock
Problem 1: (SingleTransactions)
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. i.e Maximum difference between two elements such that larger element appears after the smaller number.
Solution I
Time Complexity: O(n^2)
Solution II
Algo: Keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element).
Time Complexity: O(n)
Problem 2: (Multiple Transactions)
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Solution :
Algo:
Find the local minima and store it as starting index. If not exists, return.
Find the local maxima. and store it as ending index. If we reach the end, set the end as ending index.
Update the solution (Increment count of buy sell pairs)
Repeat the above steps if end is not reached.
Time Complexity: O(n)
Last updated