首页 > 其他 > 详细

Best Time to Buy and Sell Stock(动态规划)

时间:2014-12-28 18:11:28      阅读:241      评论: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.

思路:变相的求最大子数组,是算法导论上的例题,书上用分治法做的。

若prices=[1,4,2,8,1],每两数相减所得的利润,即头一天买入,第二天卖出。

profit=[0,3,-2,6,-7],可以看到第一天买入,最后一天卖出的profit为3+(-2)+6+(-7)=0

代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int len=prices.size();
        int res=0;
        int temp=0;
        if(len==0) return res;
        vector<int> profit(len,0);
        vector<int> dp(len,0);
        for(int i=0;i<len;++i){
            if(i==0) {profit[i]=0;continue;}
            profit[i]=prices[i]-prices[i-1];
        }
        
        dp[0]=profit[0];
        for(int i=1;i<len;++i){
            dp[i]=max(dp[i-1]+profit[i],profit[i]);
            if(dp[i]>res)
                res=dp[i];
        }
        return res;
    }
};

 

Best Time to Buy and Sell Stock(动态规划)

原文:http://www.cnblogs.com/fightformylife/p/4190202.html

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