123-Best Time to Buy and Sell Stock III

来源:互联网 发布:java axis2 调用wsdl 编辑:程序博客网 时间:2024/06/05 17:55
题目

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).

分析

动态规划法
整个的收益相当于[0,i]和[i,size-1]的加和

所以就要先正序求收益,再逆序求收益
最后一次遍历求和

实现
/*Author:FancyDate: 2017-03-27Algorithm: 123-Best Time to Buy and Sell Stock IIITime Complexity: 0(n)*/class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.size() == 0||prices.size()==1)            return 0;        vector<int> forProfit(prices.size(),0), backProfit(prices.size(),0);        int minPrice = prices[0];        int maxPrice = prices[prices.size()-1];        int maxPro = 0;        //[0,i] 交易的最大收益        for (int i = 1; i < prices.size(); i++)        {            minPrice = min(minPrice, prices[i]);            forProfit[i] = max(forProfit[i-1], prices[i] - minPrice);        }        //[i,size-1]交易的最大收益        for (int j = prices.size() - 2; j >= 0; j--)        {            maxPrice = max(maxPrice, prices[j]);            backProfit[j] = max(backProfit[j + 1], maxPrice- prices[j]);        }        //最大收益为max([0,i]+[i,size-1])        for (int i = 0; i < prices.size(); i++)            maxPro = max(maxPro, forProfit[i] + backProfit[i ]);        return maxPro;    }};
阅读全文
0 0
原创粉丝点击