Thief of Wealth

leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

 

Best Time to Buy and Sell Stock II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

핵심 아이디어

시간 순서대로 주식의 가격이 나열되어 있고,

한 타임당 1번의 구매와 1번의 판매밖에 할 수 없을때,

낼 수 있는 가장 큰 이익을 구하는 문제이다.

구현하려고 했을 때 쉽게 정답이 떠오르지 않아 풀이를 보았는데 놀라우리 만큼 간결했다.

그냥 값을 순회하면서 바로 다음값과의 차가 양수 일때 그 값을 더해주기만 하면 되는 것이었다.

[1,3,7,6,5,4,3,2,1] 이 주어졌다고 생각해보자.

그럼 1에사고 3이 아니라 7에 팔아야 된다는 로직을 구현해야한다고 생각할것이다.

하지만 그렇게 생각할 필요가 없었다.

1에사고 3에팔고 3에사고 7에 팔면 똑같기 때문이다!

앞으로 더욱 간단하게 생각할 수 있는 방법을 훈련해야겠다. :)

 

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let maxProfit = 0;
    for(let i=1; i<prices.length; i++){
        if(prices[i] > prices[i-1]){
            maxProfit += prices[i] - prices[i-1];
        }
        
    }
    return maxProfit;
};
profile on loading

Loading...