Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock_第1张图片

//  太暴力了!!!  
int maxProfit1(vector& prices) {
	int diff = 0, maxdiff = INT_MIN;
	for (unsigned int i = 0; i <= prices.size() - 2; i++){
		for (unsigned int j = 0; j <= prices.size() - 1; j++){
			if ((diff = prices[j] - prices[i]) > maxdiff){
				maxdiff = diff;
			}
		}
	}
	return maxdiff;
}

//运行通过,不过运行时间有点长
int maxProfit2(vector& prices) {
	int maxdiff = prices[1] - prices[0];
	int min = prices[1] > prices[0] ? prices[0] : prices[1];
	for (unsigned int i = 2; i <= prices.size() - 1; i++){
		if (prices[i] - min > maxdiff){
			maxdiff = prices[i] - min;
		}
		if (prices[i] < min){
			min = prices[i];
		}
	}
	maxdiff = maxdiff < 0 ? 0 : maxdiff;
	return maxdiff;
}

//优化了下
int maxProfit(vector& prices) {
	int maxdiff = prices[1] - prices[0];
	int min = prices[1] > prices[0] ? prices[0] : prices[1];
	for (unsigned int i = 2; i <= prices.size() - 1; i++){
		maxdiff = max(prices[i] - min, maxdiff);
		min = prices[i] < min ? prices[i] : min;
	}
	maxdiff = maxdiff < 0 ? 0 : maxdiff;
	return maxdiff;
}

你可能感兴趣的:(LeetCode)