leetcode--Best Time to Buy and Sell Stock III

来源:互联网 发布:传奇数据库下载 编辑:程序博客网 时间:2024/06/06 07:22

1.问题

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

2.分析

2.1动态规划:因为最多只能进行两次交易,也就是有前后两次交易。设f[i]为区间[0,i]的最大收益,g[i]为区间[i,n-1]的最大收益。我们可以使用动态规划来求f[i]和g[i],从左往右求f[i],从右往左求g[i],状态转移方程分别为:

f[i] = max(f[i-1],prices[i]-min);

g[i] = max(g[i+1],peak-prices[i]);

2.2贪心:也是分为前后两次交易,求前或者后的最大收益时用贪心来求。但贪心法会超时

3.实现

//动态规划
class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.size() < 2) return 0;        const int n = prices.size();        vector<int> f(n, 0);        vector<int> g(n, 0);        for (int i = 1, valley = prices[0]; i < n; ++i) {            valley = min(valley, prices[i]);            f[i] = max(f[i - 1], prices[i] - valley);        }        for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {            peak = max(peak, prices[i]);            g[i] = max(g[i+1], peak - prices[i]);        }        int max_profit = 0;        for (int i = 0; i < n; ++i)            max_profit = max(max_profit, f[i] + g[i]);        return max_profit;    }};
</pre><pre name="code" class="cpp">
//贪心class Solution {public:    int maxProfit(vector<int>& prices) {        int maxprofit = 0;        for(int i=0;i<prices.size();++i)   //i作为划分前后划分点        {            int leftProfit = subProfit(prices,0,i);                   int rightProfit = subProfit(prices,i,prices.size()-1);            maxprofit = max(maxprofit,leftProfit+rightProfit);        }        return maxprofit;    }        int subProfit(vector<int>& prices,int l,int r)    {        int min=INT_MAX,profit=0;        for(int i=l;i<=r;++i)            //还有个循环会超时        {            if(prices[i]<min)                min = prices[i];            if(prices[i]-min>profit)                profit=prices[i]-min;        }        return profit;    }};

0 0
原创粉丝点击