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

leetcode || 123、Best Time to Buy and Sell Stock III

时间:2015-04-27 11:18:37      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dp   动态规划   

problem:

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 two transactions.

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

Hide Tags
 Array Dynamic Programming
题意:给定一支股票的价格表,最多有两手交易,求最大利润。很经典的一道算法题!

thinking:

(1)读懂最多有两首交易:其实就是说第一次卖和第二次买有可能在同一天

(2)开两个数组,一个用于顺序记录到该天为止的最大收益,另一个记录该天后面的最大收益。

首先,因为能买2次(第一次的卖可以和第二次的买在同一时间),但第二次的买不能在第一次的卖左边。
所以维护2个表,f1和f2,size都和prices一样大。
意义:
f1[i]表示 -- 截止到i下标为止,左边所做交易能够达到最大profit;
f2[i]表示 -- 截止到i下标为止,右边所做交易能够达到最大profit;
那么,对于f1 + f2,寻求最大即可。

code:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size = prices.size();
        if (size == 0)
            return 0;

        vector<int> f1(size);
        vector<int> f2(size);

        int minV = prices[0];
        for (int i = 1; i < size; i++){
            minV = std::min(minV, prices[i]);
            f1[i] = std::max(f1[i-1], prices[i] - minV);
        }

        int maxV = prices[size-1];
        f2[size-1] = 0;
        for (int i = size-2; i >= 0; i--){
            maxV = std::max(maxV, prices[i]);
            f2[i] = std::max(f2[i+1], maxV - prices[i]);
        }

        int sum = 0;
        for (int i = 0; i < size; i++)
            sum = std::max(sum, f1[i] + f2[i]);

        return sum;
    }
};


leetcode || 123、Best Time to Buy and Sell Stock III

标签:leetcode   dp   动态规划   

原文地址:http://blog.csdn.net/hustyangju/article/details/45306795

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