121. Best Time to Buy and Sell Stock

Sis Ccr
1 min readSep 20, 2022

I think I can invest in shares, because now I know how to find the maximum profit :P

There is to things we need to track.

  1. buying price
  2. maximum profit

We need buying price as low as possible, so first we assume a large number for it. Once we began iteration, we will check if current price is lower than buying price? if its lower we replace our assumed Buying price with the lowest price.

Once we have our buying price, we need to calculate profit. Initially we assume 0 profit. The profit is the amount remaining by substracting the buying price from current price. In line 13 we calculate current profit. If this profit is greater than we had in maxProfit, we assigned maxProfit with current profit. As we iterate, once we find the lowest buying price it will not change. And the logic will focus on finding the maximum profit. The time complexity for this is O(n) since we iterate through every element only once.

--

--