코딩테스트
[leetcode, 121] best-time-to-buy-and-sell-stock
tree code
2022. 12. 13. 00:37
날마다 주식 종가가 담긴 prices가 주어지는데 언제 매수해서 매도하는 것이 가장 큰 수익이 나는지 구하는 문제다.
for-each문으로 prices를 돌면서 작은 값이 나오면 min에 저장하고 price와 현재까지 최소 가격인 min의 차이로 최대 수익을 구한다.
현재 가격 price에서 최소 가격인 min을 뺀 수익을 계속 비교하기 때문에 최대 수익은 기록이 되고,
최소 가격이 갱신이 되더라도 남은 price와의 차이가 적으면 수익은 갱신이 되지 않는다.
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int profit = 0;
for (int price : prices) {
if (price < min) {
min = price;
}
profit = Math.max(profit, price - min);
}
return profit;
}
Best Time to Buy and Sell Stock - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com