Algorithm/Online judge

[LeetCode] Array > Best Time to Buy and Sell Stock II

민철킹 2021. 5. 6. 15:18

leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/564/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


풀이

Greedy를 사용하여 문제를 해결하였다. 단순하게 오늘의 가격보다 내일의 가격이 높으면 매도하는 방식으로 가장 높은 이익을 구하였다.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if prices == sorted(prices, reverse=True):
            return 0
        total_prices = 0
        for i in range(len(prices)-1):
            if prices[i] < prices[i+1]:
                total_prices += prices[i+1] - prices[i]
        return total_prices
반응형