Skip to content

[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Sep 16, 2021 · 0 comments
Open

[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown #98

frdmu opened this issue Sep 16, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Sep 16, 2021

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

 

Example 1:

Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]

Example 2:

Input: prices = [1]
Output: 0

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

解法:
动态规划。代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n <= 1)  return 0;
        
        vector<vector<int>> dp(n, vector<int>(2, 0));
        dp[0][1] = -prices[0];
        dp[1][0] = max(0, prices[1]-prices[0]);
        dp[1][1] = max(-prices[0], -prices[1]); 

        for (int i = 2; i < n; i++) {
            dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i]);
            dp[i][1] = max(dp[i-1][1], dp[i-2][0]-prices[i]);
        }

        return dp[n-1][0];
    }
};
/*
dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i]);
dp[i][1] = max(dp[i-1][1], dp[i-2][0]-prices[i]);
0 <= i < n-1,   1 <= k

dp[-2][0] = dp[-1][0] = 0
dp[-2][1] = dp[-1][1] = -inf
*/

Refer:
团灭 LeetCode 股票买卖问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant