알고리즘/LeetCode
[Leetcode][자바스크립트][Easy] 121. Best Time to Buy and Sell Stock
Benjamin_Choi
2022. 1. 8. 21:03
풀이
/**
* 121_BestTimeToBuyAndSellStock.js
* Easy
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
var maxProfit = function(prices) {
let currMin = prices[0], currMax = 0, _maxProfit = 0;
prices.forEach((price) => {
if (price > currMax) {
currMax = price;
_maxProfit = Math.max(_maxProfit, currMax - currMin);
}
if (price < currMin) {
if (currMax > currMin) _maxProfit = Math.max(_maxProfit, currMax - currMin);
currMin = price;
currMax = 0;
}
});
return _maxProfit;
};
저렴할 때 사서 비쌀 때 파는 문제로 가장 이윤을 많이낸 경우를 return 해야한다.
현재 시점에서의 저렴한 가격을 currMin 으로 나타내고 현재 시점에서 비싼 가격을 currMax 로 나타냈다.
현재 가격이 currMax 보다 비싸졌거나, 현재 가격이 currMin 보다 더 저렴해졌을 때를 기준으로 가장 비싼 가격을 계산해서 result를 변경하는 방식이다. 미래에 사서 과거에 팔 수 없기때문에 현재보다 더 가격이 저렴해졌을 때는 우선 마지막 currMin 과 currMax 를 기준으로 result 를 설정해준다.
풀이2 - Refactoring
/**
* 121_BestTimeToBuyAndSellStock.js
* Easy
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
var maxProfit = function(prices) {
let currMin = prices[0], _maxProfit = 0;
prices.forEach((price) => {
if (price - currMin > _maxProfit) _maxProfit = price - currMin;
if (price < currMin) currMin = price;
});
return _maxProfit;
};
위에선 비교의 대상이 현재 가격을 기준으로 한 currMin과 currMax 였는데, 2번째 풀이에선 _maxProfit을 기준으로 비교한다. 여기서 currMax 변수를 생략할 수 있고 코드도 더 깔끔해진다.