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;
}
};