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

[leetcode] Best Time to Buy and Sell Stock IV

时间:2015-03-15 12:05:30      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Best Time to Buy and Sell Stock IV

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

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题解:

参考http://www.cnblogs.com/grandyang/p/4295761.html 和 http://blog.csdn.net/linhuanmars/article/details/23236995

技术分享
class Solution {
public:
    int solvemaxProfit(vector<int> prices) {
        int profit = 0;
        for(int i=0;i<prices.size()-1;i++) {
            if(prices[i+1]>prices[i])
                profit += prices[i+1]-prices[i];
        }
        return profit;
    }
    int maxProfit(int k, vector<int> &prices) {
        int n = prices.size();
        if(n<=0)
            return 0;
        if(k>=n)
            return solvemaxProfit(prices);
        int global[k+1] = {0};
        int local [k+1] = {0};
        for(int i=0;i<n-1;i++) {
            int tmp = prices[i+1]-prices[i];
            for(int j=k;j>=1;j--) {
                local[j]  = max(global[j-1]+max(tmp, 0), local[j]+tmp);
                global[j] = max(local[j], global[j]);
            }
        }
        return global[k];
    }
};
View Code

 

[leetcode] Best Time to Buy and Sell Stock IV

标签:

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4338934.html

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