[LeetCode#122] Best Time to Buy and Sell II

2024. 9. 16. 23:50·Algorithm/문제풀이

 

❒ Description


날짜 2024.09.16 (월)
제목 Best Time to Buy ans Sell II
링크 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
자료구조 배열 & 스택 
알고리즘 그리디
시간 복잡도 O(n)

 

이번 문제는 배열 또는 스택을 사용하여 풀이할 수 있는 문제이다.

물론 스택을 사용하면 메모리를 더 사용한다는 단점은 존재한다.

그리고 이 문제는 [LeetCode#739] Daily Temperature 풀이에서 아이디어 하나만 추가하면 된다. 

 

 

 

 

 

❒ Solution


1. Stack

public int maxProfit(int[] prices) {
    Deque<Integer> stack = new ArrayDeque<>();
    int[] result = new int[prices.length];
    for (int i = 0; i < prices.length; i++) {
        while (!stack.isEmpty() && prices[i] > prices[stack.peek()]) {
            int index = stack.pop();
            result[index] = prices[i] - prices[index];
            stack.clear(); // ← 추가 된 부분
        }
        stack.push(i);
    }
    return Arrays.stream(result).sum();
}

[LeetCode#739] Daily Temperature 풀이와 차이는 stack.clear(); 이 부분이다.

이 문제는 모든 인덱스에서 얼마의 이윤을 냈는지가 아니라 저점일 때 사고 고점일 때 파는 문제이기 때문이다.

따라서 `[1, 2 , 3]` 이런 경우에는 1에서 사서 3에서 팔기 때문에 1과 3만 신경쓰고 2는 신경쓰지 않아도 된다.

 

 

 

2. Array

public int maxProfit(int[] prices) {
    int maxProfit = 0;
    for (int i = 1; i < prices.length; i++) {
        int dailyProfit = prices[i] - prices[i - 1];
        if (dailyProfit > 0) {
            maxProfit += dailyProfit;
        }
    }
    return maxProfit;
}

스택을 사용한 풀이와 시간 복잡도는 O(n)으로 동일하지만, 배열 자료구조만 사용하였기 때문에 메모리 사용

측면에서 보다 효율적인 코드라고 할 수 있다.

 

 

 

 

 


'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#621] Task Scheduler  (0) 2024.09.17
[LeetCode#406] Queue reconstruction by height  (0) 2024.09.17
[LeetCode#55] Jump Game  (0) 2024.09.16
[LeetCode#743] Network Delay Time  (0) 2024.09.15
[Programmers#49191] 순위  (0) 2024.09.14
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#621] Task Scheduler
  • [LeetCode#406] Queue reconstruction by height
  • [LeetCode#55] Jump Game
  • [LeetCode#743] Network Delay Time
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (173)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (7)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • 친절한 SQL 튜닝 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Back-Tracking
    sliding-window
    오블완
    부분단조성
    greedy
    binarysearch
    Two-Pointer
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#122] Best Time to Buy and Sell II
상단으로

티스토리툴바