Best Time to Buy and Sell Stock

Jamie·2022년 3월 5일
0

LeetCode

목록 보기
11/18
post-thumbnail

📚문제

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

💡풀이

var maxProfit = function (prices) {
    // 주식을 사는 날을 prices[0]로 초기값으로, 팔아서 남는 이익을 profit을 0으로 초기값으로 선언한다
    // prices 반복문을 돌면서 buy보다 작은 값이 나타나면 그 요소를 buy로 재할당한다
    // buy보다 큰 값이 나타나면 두 수 사이의 차이를 profit과 비교해서 profit보다 클 경우 재할당한다
    // 반복문이 다 돌았을 때 profit 값이 0이면 0을 리턴, 아니면 profit 값을 리턴한다

    let buy = prices[0];
    let profit = 0;
    for (let i = 0; i < prices.length; i++) {
        if (buy > prices[i]) {
            buy = prices[i];
        } else {
            if (prices[i] - buy > profit) {
                profit = prices[i] - buy;
            }
        }
    }
    return profit === 0 ? 0 : profit;
};

✅ 처음에는 수익이 아니라 인덱스를 리턴하는 거라고 생각해서 한번 수정하긴 했지만 조건에 맞춰서 코드를 입력해주고 수월하게 풀었다.

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글