[리트코드] 121. Best Time to Buy and Sell Stock
121. Best Time to Buy and Sell Stock
나의 풀이
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let ans = [];
for (let i = 0; i < prices.length - 1; i++) {
let max = prices[i + 1];
for (let j = i + 2; j < prices.length; j++) {
if (max < prices[j]) max = prices[j];
}
ans.push(max - prices[i]);
}
const ret = Math.max(...ans);
return ret < 0 ? -1 : ret;
};
console.log(maxProfit([7, 6, 4, 3, 1]));
nums1을 순회하며 공통인 것을 구하고, 구한 값은 nums2에서 삭제하였다.
나의 풀이
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let result = 0;
let min = prices[0];
for (let i = 1; i < prices.length; i++) {
min = Math.min(min, prices[i]);
result = Math.max(result, prices[i] - min);
}
return result;
};
console.log(maxProfit([7, 1, 5, 3, 6, 4]));