码迷,mamicode.com
首页 > 其他好文 > 详细

【Best Time to Buy and Sell Stock】cpp

时间:2015-05-30 09:14:38      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
            if (prices.size()==0) return 0;
            int min_price = prices[0], max_profit = 0;
            for ( size_t i = 0; i < prices.size(); ++i )
            {
                min_price = std::min(min_price, prices[i]);
                max_profit = std::max(max_profit, prices[i]-min_price);
            }
            return max_profit;
    }
};

tips:

Greedy

核心在于维护两个变量:

min_price: 算上当前元素的最小值

max_profit:算上当前元素的最大利润

走完所有元素,可以获得max_profit

【Best Time to Buy and Sell Stock】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4539811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!