본문 바로가기

알고리즘

Best Time to Buy and Sell Stock II

매일 주식을 사고팔기를 할 수 있는데 한 번에 주식을 최대 1주만 보유할 수 있다.

매수 후 당일 즉시 매도할 수 있다. 달성할 수 있는 최대 이익을 찾아 반환하는 문제다.

 

예1

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.

예2

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.

예3

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

 

당연한 얘기이지만 내가 매수한 가격보다 매도할 가격이 높아야 이익을 낼 수 있다.

/**
 * @param {number[]} prices
 * @return {number}
 */
const maxProfit = function(prices) {
    if (prices.length === 1) {
        return 0
    }
    if (prices.length === 2) {
        return prices[1] > prices[0] ? prices[1] - prices[0] : 0
    }
    let max = 0
    
    for (let i = 1; i < prices.length; i++) {
        const diff = prices[i] - prices[i - 1]
        if (diff > 0) {
            max += diff
        }
    }
    
    return max
}

 

'알고리즘' 카테고리의 다른 글

OddOccurrencesInArray_Codility  (0) 2022.02.16
CyclicRotation_Codility  (0) 2022.02.15
Remove Nth Node From End of List - leetcode  (0) 2021.11.04
Valid Anagram - leetcode  (0) 2021.10.08
Single Number - XOR 연산자  (0) 2021.09.27