Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
제일 작은 값을 루프를 돌면서 저장.
현재 루프 prices 원소와 제일 작은 값의 차이를 구함.
var maxProfit = function(prices) {
let minprice = prices[0];
let maxprofit = 0;
for(let i = 0; i < prices.length; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
}
let diff = prices[i] - minprice;
if (maxprofit < diff) {
maxprofit = diff;
}
}
return maxprofit;
};