From 3f7066f13d9cb664f1904a28b4ac90cf943c500d Mon Sep 17 00:00:00 2001 From: Dohyeon Ju Date: Sun, 5 Apr 2026 04:14:30 +0900 Subject: [PATCH] Solution For Best Time to Buy And Sell Stock #221 --- best-time-to-buy-and-sell-stock/dohyeon2.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/dohyeon2.java diff --git a/best-time-to-buy-and-sell-stock/dohyeon2.java b/best-time-to-buy-and-sell-stock/dohyeon2.java new file mode 100644 index 000000000..05372e352 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/dohyeon2.java @@ -0,0 +1,24 @@ +class Solution { + // TC : O(n) + // SC : O(1) + public int maxProfit(int[] prices) { + int maximumProfit = 0; + int cursor = 0; + + // 전체를 순회하면서 이익을 검증 + for(int i = 0; i < prices.length; i++){ + int profit = prices[i] - prices[cursor]; + + // 만약 현재 값이 커서의 값보다 더 작다면 현재 값부터 비교하기 시작 + if(profit < 0){ + cursor = i; + continue; + } + + // 이전에 커서로 추정한 값이 높더라도 Math.max로 보존됨 + maximumProfit = Math.max(profit, maximumProfit); + } + + return maximumProfit; + } +}