You are given an array of integers 'prices' of size 'n', where ‘prices[i]’ is the price of a given stock on an ‘i’-th day. You want to maximize the profit by choosing a single day to buy one stock and a different day to sell that stock.
Please note that you can’t sell a stock before you buy one.
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’.
Output format :
Return the maximum profit you can achieve from this transaction.
1 <= 'n' <= 10 ^ 5
1 <= ‘prices[i]’<= 10 ^ 9
Time Limit: 1 sec
6
7 1 5 4 3 6
5
Purchase stock on day two, where the price is one, and sell it on day six, where the price is 6. Profit = 6 - 1 = 5.
5
5 4 3 2 1
0
Try out all possible ways to buy and sell the stocks.
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:-
O(n ^ 2), Where 'n' is the array ‘prices’ length.
We have two nested loops of O(n) complexity each.
O(1).
We are using some variables that take some constant space.
Hence the space complexity is O(1).