KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (487)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (432)
      • 백준 (187)
      • Programmers (105)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • C++
  • Level1
  • 수학
  • 다이나믹 프로그래밍
  • tree
  • codeup
  • LeetCode
  • 정렬
  • Level 2
  • programmers
  • 그래프
  • js
  • 백준
  • 제코베 JS 100제
  • 문자열
  • C
  • string
  • recursion
  • Level 1
  • Level 0

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Greedy / 121번 / Best Time to Buy and Sell Stock / JS

2023. 4. 1. 00:52

< 문제 바로가기 >

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock - 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 choosin

leetcode.com

 

< 문제 간단설명 >

당일의 주가들이 배열로 주어진다. 언제 매수를 해서 언제 매도를 하면 가장 큰 수익을 낼 수 있는지 확인한 후, 그 최대 수익을 반환하면 되는 문제이다.

 

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

    for(const CURRENT_PRICE of prices) {
        minPrice = Math.min(minPrice, CURRENT_PRICE);
        profit = CURRENT_PRICE - minPrice;
        maxProfit = Math.max(maxProfit, profit);
    }

    return maxProfit;
};

prices 배열을 하나씩 순회를 하는데, 그 때마다 최소값을 갱신해준다. 그와 동시에 이윤을 구해서 최대 이윤도 똑같이 갱신을 해주면 된다.

저작자표시 (새창열림)

'PS > LeetCode' 카테고리의 다른 글

LeetCode / Tree / 589번 / N-ary Tree Preorder Traversal / JS  (0) 2023.04.05
LeetCode / Greedy / 409번 / Longest Palindrome / JS  (0) 2023.04.01
LeetCode / Linked List / 142번 / Linked List Cycle II / JS  (0) 2023.04.01
LeetCode / Linked List / 876번 / Middle of Linked List / JS  (0) 2023.04.01
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Tree / 589번 / N-ary Tree Preorder Traversal / JS
    • LeetCode / Greedy / 409번 / Longest Palindrome / JS
    • LeetCode / Linked List / 142번 / Linked List Cycle II / JS
    • LeetCode / Linked List / 876번 / Middle of Linked List / JS
    KimMinJun
    KimMinJun

    티스토리툴바