(Python, Java) 리트코드 - Best Time to Buy and Sell Stock II

[문제 링크]

Python 풀이

from typing import List

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(len(prices) - 1):
            if prices[i] < prices[i + 1]:
                profit += prices[i + 1] - prices[i]

        return profit

Java 풀이

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int idx = 0; idx < prices.length - 1; idx++) {
            if (prices[idx] < prices[idx + 1]) {
                profit += prices[idx + 1] - prices[idx];
            }
        }
        return profit;
    }
}

다음날 이익이 난다면 파는 형식의 그리디 알고리즘이다.


© 2021. By Backtony