[leetcode] 121. Best Time to Buy and Sell Stock _ Algorithm Problem Solve for python



1. Problem

121. Best Time to Buy and Sell Stock

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 <= 10^5
  • 0 <= prices[i] <= 10^4

2. Solution

I solve this problem like this.

2.1. Time Limit Exceeded Solution

First i solve this problem like this way. But, this solution is so slow.

  • Complexity
    • Time complexity : O(N^2)
    • Space complexity : O(N)
  • Step
    • By looping through the for statement, we find the value of max each time.
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        answer = 0
        for idx, price in enumerate(prices[:-1]):
            answer = max(max(prices[idx+1:]) - price, answer)
        return answer
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) <= 1:
            return 0
        maxx = max(prices[1:])
        answer = maxx - prices[0] if maxx - prices[0] > 0 else 0
        
        for idx, price in enumerate(prices[1:-1]):
            if price >= maxx:
                maxx = max(prices[idx+1 + 1:])
            answer = max(answer, maxx - price)

        return answer

2.2. Make the largest of the values after the array index

This solution can solve this problem.

  • Complexity
    • Time complexity : O(N)
    • Space complexity : O(N)
  • Step
    • By looping through the for statement from the back, i make a max_list.
    • Check prices
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        answer = 0

        if len(prices) <= 1:
            return 0
            
        max_list = [prices[-1]]
        for price in prices[:-1][::-1]:
            max_list.append(max(max_list[-1], price))
        max_list.reverse()

        for idx, price in enumerate(prices[:-1]):
            answer = max(answer, max_list[idx+1] - price)

        return answer

2.3. Easy Math Approach

I check other user’s solution. This is more best. Space complexity is O(1).

  • Complexity
    • Time complexity : O(N)
    • Space complexity : O(1)
  • Step
    • renew buy, sell value while for statement
      • price < buy : now price is lower than before buy value, so change buy price.
      • price > sell : now price is bigger than before sell value, so change sell value.
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy, sell = prices[0], prices[0]
        current_profit = sell - buy
        for price in prices:
            if price < buy:
                buy = price
                sell = price
            if price > sell: 
                sell = price
            if sell - buy > current_profit:
                current_profit = sell - buy
        return current_profit