思路:用一个变量记录最小值,一个变量记录最大收益,从头到尾扫描一次价格,当扫描到第i天的价格时,如果这个价格比最小值小,则替换,如果比最小值大,则计算此刻的收益是否大于最大收益,大于则替换,否则继续。
class Solution {public:int maxProfit(vector<int> &prices) {int profit = 0;int minIndex = 0;for (size_t i = 1; i < prices.size(); i++){if (prices[i] < prices[minIndex]){minIndex = i;}else if (prices[i] - prices[minIndex] > profit){profit = prices[i] - prices[minIndex];}}return profit;}};
Best Time to Buy and Sell Stock
原文:http://www.cnblogs.com/flyjameschen/p/fc52ba9c5d9bf3e05afc6ddc75d4ae58.html