[leetcode-123]Best Time to Buy and Sell Stock III(c++)

问题描述:
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).

Show Tags
Show Similar Problems

分析:这道题非常的巧妙,题目中说最多分两段进行,那么肯定在一个节点前,买入之后再卖出,然后在这个节点之后,先买入后卖出。
那么就可以维护两个数组,第一个数组是指,从前向后遍历,在某个节点之前能获取的最大收益。第二个数组指:从后向前遍历,在某个节点之后获取的最大收益。使用DP算法来获取者两个数组,然后在两个数组中找到某个节点,使两个数组的对应项相加和最大。即找到了最大收益值。

代码如下:12ms

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int length = prices.size();
        if (length <= 0)
            return 0;
        int *front = new int[length];
        int *end = new int[length];

        int low = prices[0];
        int height = prices[0];
        front[0] = 0;
        for (int i = 1; i < length; i++) {
            int tmpVal = prices[i] - low;
            front[i] = front[i - 1] > tmpVal ? front[i - 1] : tmpVal;
            if (prices[i] < low)
                low = prices[i];
        }
        height = prices[length - 1];
        low = prices[length - 1];
        end[length - 1] = 0;
        for (int i = length - 2; i >= 0; i--)
        {
            int tmpVal = height - prices[i];
            end[i] = end[i + 1]>tmpVal ? end[i + 1] : tmpVal;
            if (prices[i] > height)
                height = prices[i];
        }
        int max = front[0] + end[0];
        for (int i = 1; i < length; i++) {
            if (front[i] + end[i]>max)
                max = front[i] + end[i];
        }
        return max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值