Best Time to Buy and Sell Stock
2015-04-07 21:46 笨笨的老兔子 阅读(204) 评论(0) 收藏 举报给定一个向量,该向量表示一只股票在第i天的价格,y要使得股票收益最大就应该在第i天买入,第i+n天卖出,求最大收益的值是多少
思路:用一个变量记录最小值,一个变量记录最大收益,从头到尾扫描一次价格,当扫描到第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;}};
浙公网安备 33010602011771号