[LeetCode] Best Time to Buy and Sell Stock

int maxProfit(vector<int> &prices) {
	if (prices.empty())
	{
		return 0;
	}
	vector<int> profits;
	profits.push_back(0);
	vector<int>::iterator iter;
	for(iter = prices.begin(); iter != prices.end()-1; iter++)
	{
		int profit = *(iter+1) - *iter;
		profits.push_back(profit);
	}
	int sum = 0,max = 0;
	for(iter = profits.begin(); iter != profits.end(); iter++)
	{
		if(sum + *iter >= 0)
		{
			sum += *iter;
		}
		else
		{
			sum = 0;
		}
		if(sum > max)
		{
			max = sum;
		}             
	}
	return max;
}

最初,用两层循环暴力求解最大收益,结果果然Time Limit Exceeded;
之后,还是套用最大子数组的思路,不过忘了考虑prices为空的情况,Runtime Error了一次。。
最后,加上异常处理,终于Accepted了。

你可能感兴趣的:(LeetCode)