121. 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 choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
i
번째 주식 가격을 담은 행렬 prices
0
을 반환함min
= prices[0]
, maxProfit
= 0
(기본값) 으로 설정min
보다 가격이 작을 경우, min
값을 해당 값으로 할당 (최소값 갱신)maxProfit
보다 price[i] - min
이 클 경우, maxProfit
에 price[i] - min
값을 할당 (최대 이익 갱신)maxProfit
반환class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
continue;
}
if (prices[i] - min > answer) {
maxProfit = prices[i] - min;
}
}
return maxProfit;
}
}
Math.max()
, Math.min()
을 사용하여 코드의 가독성을 증대함class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
min = Math.min(prices[i], min);
maxProfit = Math.max(prices[i] - min, maxProfit);
}
return maxProfit;
}
}