LeetCode Best Time to Buy and Sell Stock (JavaScript)

2025. 12. 28. 16:28·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

문제 설명

더보기

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

문제 풀이

1. (시간 초과)

최대 수익을 계산하기 위해 현재 값(i)와 i 이후의 배열의 최대 값을 구해서 계산하는 방식

prices에서 i 다음 값들 중 최대 값을 구하기 위해 `slice`를 통해 계산하는 방식은 총 O(n^2)의 시간 복잡도를 가지기 때문에

prices의 길이가 길면 시간 초과의 문제가 발생

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let profit = 0;

    for (let i = 0; i < prices.length; i++) {
        const price = Math.max(...prices.slice(i + 1));
        profit = Math.max(profit, price - prices[i]);
    }

    return profit;
};

 

2. (해결)

O(n)의 시간 복잡도로 문제를 해결할 수 있는 로직으로 수정

배열의 뒤 부터 계산하면서 최대 이윤을 계산하기 위해 maxPrice를 통해 현재 타겟이될 최대 값을 갱신하도록 함

이후 i번째와 maxPrice의 차이를 통해 최대 이윤 profit을 계산하도록 함

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let profit = 0;

    let maxPrice = prices[prices.length - 1];

    for (let i = prices.length - 2; i >=0; i--) {
        profit = Math.max(profit, maxPrice - prices[i]);

        maxPrice = Math.max(maxPrice, prices[i]);
    }

    return profit;
};

결론

최대 이윤을 계산하기 위해 maxPrice를 최대로 갱신해주는 부분이 이 문제를 해결하는 핵심부분

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Number of Islands (JavaScript), DFS  (1) 2026.01.27
LeetCode Valid Palindrome (JavaScript)  (0) 2026.01.26
LeetCode Decode Ways (JavaScript), (DFS, Memoization)  (0) 2025.12.22
LeetCode Triangle (JavaScript)  (0) 2025.12.19
LeetCode Subsets ll (JavaScript), backtracking  (0) 2025.12.18
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Number of Islands (JavaScript), DFS
  • LeetCode Valid Palindrome (JavaScript)
  • LeetCode Decode Ways (JavaScript), (DFS, Memoization)
  • LeetCode Triangle (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (218)
      • 프론트엔드 (65)
        • JavaScript (52)
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (131)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (42)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Best Time to Buy and Sell Stock (JavaScript)
상단으로

티스토리툴바