PS/LeetCode

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

KimMinJun 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 배열을 하나씩 순회를 하는데, 그 때마다 최소값을 갱신해준다. 그와 동시에 이윤을 구해서 최대 이윤도 똑같이 갱신을 해주면 된다.