리트코드/easy
[리트코드] 121. Best Time to Buy and Sell Stock - js
bbeyak
2023. 8. 29. 12:39
반응형
1. 문제
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
2. 코드
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let max = 0;
let maxProfit = 0;
for(let i=prices.length-1;i>=0;i--){
if(prices[i] > max){
let bigger = false;
for(let j=i-1;j>=0;j--){
if(prices[j] < prices[i]){
bigger = true;
break;
}
}
if(bigger) max = prices[i];
}else{
if(max - prices[i] > 0 && max - prices[i] > maxProfit)
maxProfit = max - prices[i];
}
}
return maxProfit;
};
반응형