[LC] 121. Best Time to Buy and Sell Stock

Tech

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

Approach

I just simply thought I can get the minimum so far and find the max profit comparing minimum and max so far. Let says best[i] is the best profit at ‘i’. Then, best[i] = max_from_right[i] – min_from_left[i]. So, like the “Trapping rainwater” problem, I first calculate every min/max values from both left and right.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        minvalues, maxvalues = [sys.maxsize], [-1]
        n = len(prices)
        
        flag = False
        for i in range(1, n+1):
            minvalues.append(min(minvalues[i-1], prices[i-1]))
            maxvalues.append(max(maxvalues[i-1], prices[n-i]))
            
        maxvalues.reverse()    
        #print(minvalues, maxvalues)
        maxprofit = 0
        for i in range(0, n):
            #print(maxvalues[i], minvalues[i])
            maxprofit = max(maxvalues[i] - minvalues[i], maxprofit)
        return maxprofit

Actually, it passed all test cases. However, it seems very slow. It just faster than 7% of online submission and I think I can make a better way. Since there is two for loop, I think I can use a single loop. Maybe I don’t need to calculate every max value so far from right since the current prices will be the potential max value while calculating the min value so far. So, in the position of “i,” not a best but best_guessing[i] = prices[i] – min_so_far In that case, whenever we find prices is maxed value, then we can get the max profit. Here is my final submission

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_so_far = sys.maxsize
        maxprofit = 0
        
        for price in prices:
            if price < min_so_far:
                min_so_far = price
            else:
                maxprofit = max(price - min_so_far, maxprofit)
        return maxprofit

Time/Space Complexity: O(N)

Submission
Runtime: 1036 ms, faster than 29.30% of Python3 online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 25.2 MB, less than 5.44% of Python3 online submissions for Best Time to Buy and Sell Stock.


Leave a Reply

Your email address will not be published. Required fields are marked *