![]() |
VOOZH | about |
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.
Below is the implementation of the above approach:
865
If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times.
Following is the algorithm for this problem.
Buy on day: 0 Sell on day: 3 Buy on day: 4 Sell on day: 6
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!