Leetcode - 121. Best Time to Buy and Sell Stock

숲사람·2022년 6월 7일
0

멘타트 훈련

목록 보기
49/237

문제

idx가 날짜고, 값이 가격인 배열이 주어질때, 가장 쌀때 사서 비쌀때 판다고 할때 가장큰 수익은?

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.

해결

#define max(a,b) (((a) > (b)) ? (a) : (b))
int maxProfit(int* prices, int pricesSize){
    int min_val = INT_MAX;
    int max_val = 0;

    for (int i = 0; i < pricesSize; i++) {
        if (prices[i] < min_val)
            min_val = prices[i];
        else
            max_val = max(prices[i] - min_val, max_val);
    }
    return max_val;
}

230104 다시 풀어봄

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int max_p = 0;
        int cur_min = prices[0];
        
        for (int i = 1; i < prices.size(); i++) {
            cur_min = std::min(cur_min , prices[i]);
            max_p = std::max(max_p, prices[i] - cur_min);
        }
        return max_p;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글