How to get maximum profit by buying and selling a stock when at most one transaction is allowed?
In this problem, we have given an array of stock prices, the ith element represents the stock price on ith day.
If we are allowed 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.
Note that you cannot sell a stock before you buy one. If it’s not possible to achieve any profit return 0.
For example –
Example 1-
Input – { 9, 1, 6, 3, 7, 4}
Output – 6 (Buy on day 2 (1) and sell on day 5 (7))
Example 2-
Input – {5, 4, 3, 2, 1}
Output – 0 (It is not possible to do any transaction)