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

Jaeho Kim·2024년 1월 15일
0

코딩테스트

목록 보기
110/110

	public static int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }

        int maxProfit = 0;
        int minPrice = prices[0];

        for (int price : prices) {
            int profit = price - minPrice;
            maxProfit = Math.max(maxProfit, profit);
            minPrice = Math.min(minPrice, price);
        }

        return maxProfit;
    }

문제 자체는 쉬웠으나 brute force 방식으로 접근하였을떄 시간복잡도에서 문제가 발생되었다. 이를 줄이는 과정에서 "카데인알고리즘"을 알게되었다.

시간을 절약하기 위해 무언가를 기억하는 것.
중복되는 연산 줄이기

profile
Hello, World!

0개의 댓글

관련 채용 정보