Skip to content

홍성우_Best Time to Buy and Sell Stock#42

Open
hsw824 wants to merge 2 commits intomainfrom
hsw-2
Open

홍성우_Best Time to Buy and Sell Stock#42
hsw824 wants to merge 2 commits intomainfrom
hsw-2

Conversation

@hsw824
Copy link
Copy Markdown

@hsw824 hsw824 commented Jul 30, 2025

🧑‍💻 언어 및 제출 결과

  • 사용 언어: TypeScript, ...
  • 통과 여부: ❌

🧠 풀이 설명

  1. 제일 가격이 싼날을 따로 추출
  2. 그 이전은 배열에서 다 날려버림

ex) [7, 1, 5, 3, 6, 4] → 1이 제일 작음 7, 1 날려버리기 [5, 3, 6, 4]

  1. 작은 배열을 뺀 중 제일 큰 수를 추출
  2. 추출한 값을 빼서 반환
  3. 가격이 제일 싼 날의 인덱스가 마지막 인덱스라면 return 0

내가 푼 코드

function maxProfit(prices: number[]): number {

    const min = Math.min(...prices)
    const deleteCount =  prices.findIndex((item)=> item === min ) + 1

    if(deleteCount === prices.length){
        return 0
    }

    prices.splice(0, deleteCount)
    const max = Math.max(...prices)

    return max - min
};

이렇게 했을 경우 [7,1,5,3,6,4], [7,6,4,3,1]은 내가 원하는대로 답이 잘 나왔는데 [2,4,1]에서는 답이 제대로 나오지 않았다. 최소 가격과 최대 가격만 비교하는게 아니라 계속 빼기를 해서 결과를 낸 다음에 그 값이 제일 큰 경우를 반환하는게 옳다고 생각했다.

실제 정답 코드

function maxProfit(prices: number[]): number {
    let minPrice = prices[0]
    let maxPrice = 0

    for(let i = 1; i < prices.length; i++ ){
        maxPrice = Math.max(maxPrice, prices[i] - minPrice)
        minPrice = Math.min(prices[i], minPrice)
    }

    return maxPrice
};

📊 시간/공간 복잡도

✅ 어떠한 근거로 시간/공간 복잡도가 이렇게 나왔는지 설명해주세요.

⚡️ 풀이의 속도와 메모리 등을 캡쳐해서 올려주세요.

  • 시간 복잡도: O(n)
  • 공간 복잡도: O(1)
image

📝 추가 설명 (선택)

  • 고민했던 포인트가 있다면 간단히 적어주세요.

🙋‍♂️ 리뷰어에게

  • 리뷰어가 보면 좋을 포인트, 질문, 궁금한 점 등을 작성해 주세요.

@github-actions github-actions bot added the TeamB label Jul 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant