[알고리즘] LeetCode - Best Time to Buy and Sell Stock

Jerry·2021년 1월 13일
0

LeetCode

목록 보기
15/73
post-thumbnail

LeetCode - Best Time to Buy and Sell Stock [난이도:Easy]

문제 설명

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

You are only permitted to complete at most one transaction. In other words, you can buy one and sell one share of the stock. You cannot sell a stock before you buy one.

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.
The answer is not 7-1 = 6, as selling price needs to be larger than buying price.

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

제약사항

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

Solution

var maxProfit = function(prices) {
    
    let lowVal=prices[0]; // 첫번째 할당
    // let highVal = lowVal;
    
    let maxProfit = 0;
    
    for(let i=1; i<prices.length; i++){
        if (prices[i]<lowVal) {  // 최소값보다 작은 숫자면, 이후의 나오는 숫자들과 이전 최소값보다 항상 큰 차이를 가지기 때문에 lowVal을 바꿔줌
            lowVal = prices[i];
        }  
        else if (prices[i] - lowVal > maxProfit) { // if -> else if 로 변경. 최소값이 변경되는 경우에는 항상 "prices[i] - lowVal" 이 0이므로 if 절을  수행할 필요가 없으므로
            maxProfit = prices[i] - lowVal;
        }

    }

    return maxProfit;   
};

^~^

profile
제리하이웨이

0개의 댓글