


The first line contains an integer ‘n’ denoting the size of the array ‘prices’.
The second line includes ‘n’ integers denoting the elements of the array ‘prices’.
Return the maximum profit you can achieve from this transaction.
1 <= 'n' <= 10 ^ 5
1 <= ‘prices[i]’<= 10 ^ 9
Time Limit: 1 sec
As seen from the sample input-output examples, a possible approach would be to buy a stock, sell it on every possible day whenever profitable, and keep updating the maximum profit so far.
This will require two nested loops. The outer one will pick up each day, say I, one by one to purchase that stock, and the inner loop will calculate the profit if the stock is sold on each possible day.
The steps are as follows:-
It is always profitable to buy a stock when its price is the lowest in the past.
Taking an example for understanding, ‘prices’ = [7, 1, 5, 4, 3, 6].
Max profit on Day 3 = Stock price on Day 3 - Minimum of the Stock price of Day 1 and Day 2 = 5 - 1 = 4.
Max profit on Day 4 = Stock price on Day 4 - Minimum of the Stock price of Day 1, Day 2, and Day 3 = 4 - 1 = 3.
In general, max profit on Day n = Price of stock on Day n - min(Day 1, Day 2, ………., Day n-1).
So our idea is to buy the stock at the lowest price that has occurred in the past and sold it on the current day. This operation can be performed on every possible day and the maximum profit among them can be stored as the answer to the problem.
To achieve it, we iterate over the ‘prices’ array linearly and keep a variable storing the value of the least price that has occurred in the past.
We calculate the profit if we sell at the current point of time and buy at the least price in the past, and update our maximum profit.
The steps are as follows: