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

Joy·2022년 10월 13일
0

Coding Test

목록 보기
47/48

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.

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        buy = prices[0]
        profit = 0
        for i in range(1,len(prices)):
            buy = min(buy, prices[i])
            profit = max(profit, prices[i]-buy)
        return profit

set purchase price to price from first day, profit to 0
loop every prices from the 2nd day,
compare purchase price and update purchase price to smaller price.
compare current profit to difference of current price and purchase price

profile
roundy

0개의 댓글