LintCode 151. Best Time to Buy and Sell Stock III

原题

LintCode 151. Best Time to Buy and Sell Stock III

Description

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.

Notice

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

Example

Given an example [4,4,6,1,1,4,2,5], return 6.

解题

给出股票价格的变化,只能每天只能买入或卖出一次,求利润最大值。
要求总交易次数不超过两次,且必须处理完一次交易后(买入并卖出后)才能继续下一次交易。

要求两次交易之间没有重合,那么可以采用分治的方法。将数组以i为借分为两个部分求出这两个部分的最大利润,再相加。

定义front[i]表示0 到 i的最大利润,back[i]表示i 到 n - 1的最大利润,然后再对所有i进行一次遍历,取front[i] + back[i]的最大值即可。

front[i]back[i]可以用动态规划的思想计算。

代码

class Solution {
public:
    /*
    * @param prices: Given an integer array
    * @return: Maximum profit
    */
    int maxProfit(vector &prices) {
        // write your code here
        if (prices.size() < 2) return 0;
        vector front(prices.size()), back(prices.size());
        for (int i = 1, minPrice = prices.front(); i < prices.size(); i++) {
            minPrice = min(minPrice, prices[i]);
            front[i] = max(front[i - 1], prices[i] - minPrice);
        }

        for (int i = prices.size() - 2, maxPrice = prices.back(); i >= 0; i--) {
            maxPrice = max(maxPrice, prices[i]);
            back[i] = max(back[i + 1], maxPrice - prices[i]);
        }

        int res = 0;
        for (int i = 0; i < prices.size(); i++) {
            res = max(res, front[i] + back[i]);
        }
        return res;
    }
};

你可能感兴趣的:(LintCode 151. Best Time to Buy and Sell Stock III)