121. Best Time to Buy and Sell Stock

leetcode url

Solutions

int maxProfit(vector<int> &prices) {
	int max_profit = 0;
	int min_price = INT_MAX;
	int profit = 0;
	int prices_size = prices.size();
	if (prices_size < 2) {
		return 0; 
	}
	for (int i = 0; i < prices_size; ++i) {
		min_price = min(min_price, prices[i]);
		profit = prices[i] - min_price;
		if (profit > 0) {
			max_profit = max(profit, max_profit);
		}
	}
	return max_profit;
}