123.leetcode Best Time to Buy and Sell Stock III(hard)[动态规划算法 数组]

来源:互联网 发布:star法则java简历范文 编辑:程序博客网 时间:2024/06/06 05:35

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

Subscribe to see which companies asked this question

具体思路:这道题的含义首先是最多只能进行两次交易,因此不像可以无上限交易的Best Time to Buy and Sell Stock II一样采用贪心的策略,应该选择一个合适的第一次交易与第二次交易的分界点。这里采用两个动态数组来完成,第一个dp1保存从0开始到i为止获得的一次交易的最大利益,dp2保存从i开始到n-1为止获得的一次交易的最大利益。最后的最大利益就是对每个i节点dp1[i]+dp2[i]的和最大的i节点。

class Solution {public:    int getMax(int a,int b)    {        if(a>b) return a;        else  return b;    }    int maxProfit(vector<int>& prices) {        //动态规划,采用两个状态标识,一个是dp1[n]表示在dp[i]之前的最大收益与I那个算法差不多,dp2[n]表示dp[i]之后一次交易的最大收益        int result = 0;        int n = prices.size();        if(n<=1) return 0;        int dp1[n];        int dp2[n];        memset(dp1,0,sizeof(dp1));        memset(dp2,0,sizeof(dp2));        int start = prices[0];        for(int i= 1;i<n;i++)        {            if(start > prices[i])                    start = prices[i];            dp1[i] = getMax(dp1[i-1],prices[i]-start);        }                int last = prices[n-1];        for(int i= n-2;i>=0;i--)        {            if(last<prices[i])                 last = prices[i];            dp2[i] = getMax(dp2[i+1],last-prices[i]);        }                for(int i=0;i<n;i++)        {            if((dp1[i]+dp2[i])>result) result = dp1[i]+dp2[i];        }        return result;            }};


0 0