https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/564/
현재 날짜의 최대수익을 가지고 있으면된다!
/**
* @param {number[]} prices
* @return {number}
*/
const maxProfit = function (prices) {
const i번째까지의최대수익 = Array.from({ length: prices.length }, () => 0);
for (let i = 1; i < prices.length; i++) {
i번째까지의최대수익[i] =
i번째까지의최대수익[i - 1] +
(prices[i] - prices[i - 1] >= 0 ? prices[i] - prices[i - 1] : 0);
}
return i번째까지의최대수익[i번째까지의최대수익.length - 1];
};
console.log(maxProfit([7, 1, 5, 3, 6, 4]));
console.log(maxProfit([1, 2, 3, 4, 5]));
console.log(maxProfit([7, 6, 4, 3, 1]));
'개발 > 알고리즘' 카테고리의 다른 글
[LeetCode] Rotate Array (0) | 2021.07.10 |
---|---|
[프로그래머스] 괄호변환 (2) | 2021.07.08 |
[LeetCode] 111. Minimum Depth of Binary Tree (트리 깊이 구하기) (0) | 2021.03.15 |
[LeetCode] 101. Symmetric Tree (0) | 2021.01.27 |
[LeetCode] 122. Best Time to Buy and Sell Stock II (0) | 2021.01.26 |