본문 바로가기

Algorithm/Greedy

(C++) - LeetCode (easy) 121. Best Time to Buy and Sell Stock

반응형

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

 

Best Time to Buy and Sell Stock - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

greedy로 해결했습니다.

📕 풀이방법

📔 입력 및 초기화

저점 매수를 의미하는 변수 buy와 정답 ans를 선언 후 초기화해줍니다.

📔 풀이과정

1. prices의 원소를 순회합니다.

    1-1 저점을 발견하면 buy에 최솟값을 저장해줍니다.

     1-2 얻을 이익 = 현 고점 - 현 저점입니다. 이 값이 ans보다 크면 ans를 해당값으로 갱신해줍니다.

📔 정답출력

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy = prices[0];
        int ans = 0;
        for(int i = 0; i < prices.size(); i++){
            buy = min(buy, prices[i]);
            int curProfit = prices[i] - buy;
            ans = max(ans, curProfit);
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.