121. Best Time to Buy and Sell Stock
Given an array prices
where prices[i]
is the price of a given stock on the ith
day. Return the maximum profit that can be achieved by buying on one day and selling on another.
Intuition
To identify the max profit, we need to buy on the day when price is lowest & sell on the day its highest till the day
i
.
Approach
Iterate over the array store the
minPrice
&maxPrice
seen till now.If we have to change the
minPrice
it mean we are buying on that day somaxPrice
also needs to be reset.
Complexity
Time complexity : $\text{O}(n)$
We iterate over the prices only once.
Space complexity : $\text{O}(1)$
There is no extra space needed.
Code
Last updated