Algolithm-Leetcode/Sliding Window
Best Time to Buy and Sell Stock
꿀잠마스터
2026. 7. 29. 00:24
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Best Time to Buy and Sell Stock - LeetCode
Can you solve this real interview question? Best Time to Buy and Sell Stock - 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 choosin
leetcode.com
주식의 판매 금액을 배열로 주고 가장 이득을 보는 경우의 이익 값을 찾는 문제이다.
배열의 인덱스를 적절하게 조절하여 문제를 풀어야 했다.
가장 쌀 때 사서 비싸게 파는 경우를 찾는 문제이므로, 파는 것을 기준으로 순회 하였으면,
값을 체크해서 가장 낮은 금액일 경우 해당 금액을 사는 날로 변경하였다.
시간의 개념이 들어가므로 파는 날짜보다 사는 날짜가 이전에 있어야 하기 때문에 무작정 최소 값을 사는 기준으로 하는 것이 아니라 파는 날짜를 순회해서 기준이 되는 날짜를 찾았다.
public class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = prices[0];
int buy = 0;
// 매일 파는 값을 체크, 사는 지점은 값(minPrice)이 가장 낮은 지점일 때
for(int sell = 1; sell < prices.length; sell++){
int buyPrice = prices[buy];
int sellPrice = prices[sell];
int curProfit = sellPrice - buyPrice;
// 최저가일 경우 구매점으로 변경
if(sellPrice < minPrice){
buy = sell;
minPrice = sellPrice;
continue;
}
maxProfit = Math.max(curProfit, maxProfit);
}
return maxProfit;
}
}