首页 > 其他 > 详细

[LeetCode] Best Time to Buy and Sell Stock

时间:2015-08-13 18:07:03      阅读:190      评论:0      收藏:0      [点我收藏+]

Best Time to Buy and Sell Stock

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) {
        int len = prices.size();
        if(len==0 || len==1){
            return 0;
        }
        int maxProfit = 0;
        int minPrices = prices[0];
        for(int i=1; i<len; i++){
            minPrices = min(minPrices, prices[i]);
            maxProfit = max(maxProfit, prices[i] - minPrices);
        }
        return maxProfit;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Best Time to Buy and Sell Stock

原文:http://blog.csdn.net/kangrydotnet/article/details/47615019

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!