LeetCode 123. Best Time to Buy and Sell Stock III

题目链接:

https://leetcode.com/problems/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.

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

Example 1:


Example 2:


Example 3:

这又是一道动态规划的题目:

c++

class Solution {
public:
    int dp[100005][2];
    int maxProfit(vector<int>& prices) {
        
        memset(dp,0,sizeof(dp));
        int l = prices.size();
        for(int i=1;i<l;i++)
        {
            for(int j=i-1;j>=0;j--)
            {
                dp[i][0] = max(dp[i][0],max(dp[j][0],prices[i]-prices[j]));
                if(i-3>=0&&j>=1&&dp[j-1][0]>0)
                dp[i][1] = max(dp[i][1],max(dp[j][1],dp[j-1][0]+prices[i]-prices[j]));
            }
        }
        
        return max(dp[l-1][0],dp[l-1][1]);
        
    }
};

原文地址:https://www.cnblogs.com/dacc123/p/9328994.html