Find Best Time To Buy and Sell Stock

Given an array of integers that are the stock prices, find the max profit that you can achieve by buying a stock and selling stock at a later date. The progression of the array indicates the progression of time. This problem can be found in leetcode at this link .

Solution: Solution

class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) best_buying_price = prices.copy() for i in range(1,n): best_buying_price[i] = min(best_buying_price[i-1],prices[i]) profit = 0 for idx in range(n): pr = prices[idx]-best_buying_price[idx] if pr > profit: profit = pr return profit

In the above code, what we do is we create an array to have the best possible price to buy the stock. We iterate again through this loop and the main price loop to find the profit to maximize.

Solution: More Optimized Solution

In the following code, we run only one loop wherein we find the best time to buy the stock. If the current time is not the best time to buy the stock, then it is possible candidate for selling stock. If the profit is maximixed, we can sell it. This way we can run just one for loop.

class Solution: def maxProfit(self, prices: List[int]) -> int: profit=0 buying_price=float("inf") for price in prices: if price < buying_price: buying_price = price elif price - buying_price > profit: profit = price-buying_price return profit