ALGORITHM/Java algorithm

[JAVA][LeetCode][SlidingWindow] #122. Best Time to Buy and Sell Stock II

호이호이호잇 2024. 4. 14. 13:35
728x90
반응형

문제 / 예시 / 제한조건 : 

 

지난 번 문제에서 조오금 발전한 문제!

여러번 사고 팔 수 있고, 제일 큰 합을 리턴하면 되는 문제.

 

여러가지 예시를 해본 결과

- sell 하는 경우 : 현재의 가격이 다음날의 가격보다 비쌀 경우. -> 다음날에 다시 buy 하면 됨.

                         : 끝까지 다 확인 했을 경우.

 

7 1 5 3 6 4 를 예로 든다면,

----

buy : 7

sell : 1 

- sell(1)< buy(7)

-> buy = sell (1)  / sell = buy + 1 (5)

----

buy : 1

sell : 5

- sell(5) > buy(1)

- Profit = sell(5) - buy(1) = 4

- check next sell : nextSell(3) < sell(5) -> buy = current sell(5) / sell = buy + 1 (6)

----

buy : 5

sell : 3

- sell(3)< buy(5)

-> buy = sell (3)  / sell = buy + 1 (6)

----

buy : 3

sell : 6

- sell(6) > buy(3)

- Profit =  Profit + sell(6) - buy(3) = 7

- check next sell : nextSell(4) < sell(6) -> buy = current sell(6) / sell = buy + 1 (4)

 ----

buy : 6

sell : 4

- sell(4)< buy(6)

-> buy = sell (4)  / sell = buy + 1 (X)

----

 

이런식으로 하면 된다.

 

나는 한 번에 통과!


int maxProfit = 0;

int buyTime = 0, sellTime = 1;
while (sellTime < prices.length) {
    if (prices[sellTime] < prices[buyTime]) {
        buyTime = sellTime;
        sellTime++;
    } else {
        if (sellTime < prices.length - 1 && prices[sellTime] > prices[sellTime + 1]) {
            maxProfit += (prices[sellTime] - prices[buyTime]);
            buyTime = sellTime;
            sellTime = buyTime + 1;
        } else if (sellTime >= prices.length - 1) {
            maxProfit += prices[sellTime] - prices[buyTime];
            sellTime++;
        } else {
            sellTime++;
        }
    }
}

return maxProfit;
  • Time Complexity: O(n)
  • Space Complexity: O(1)

다른 사람들의 솔루션과 다른 유튜브 보면서 내가 한 방식 외에 다른 방식이 있는지 체크해봐야겠다.

 

leetcode 다른 사람 솔루션 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solutions/4866230/java-greedy-solution-with-detailed-explanations/

- 내가 한 방식 :  sellPoint를 잡아서 다음 포인트와 비교하니까 if 문을 세개로 나눠야해서 지저분

- 솔루션 방식 : sellPoint 가 아닌 다음 포인트를 기준으로 비교해서 깔끔!

 

728x90
반응형