Problem Solving/LeetCode

[LeetCode] C++ 121. Best Time to Buy and Sell Stock

LeeJaeJun 2024. 8. 16. 00:39
728x90
반응형

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

문제

 

문제 분석

1. 가장 작은 값을 계속 갱신해가며 profit을 구하면 됩니다. 배열 순서대로 진행하면 이전의 결과와 차이를 계산하지 않고 계속 배열 뒤쪽의 값들과만 계산할 수 있습니다.

 

풀이

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min = 10000;
        int profit = 0;

        for(const auto& price: prices){
            if(price < min){
                min = price;
            }

            int temp = price - min;
            if(profit < temp){
                profit = temp;
            }
        }

        return profit;
    }
};

728x90
반응형