Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:windows 2003 编辑:程序博客网 时间:2024/06/04 20:20

Say you have an array for which the ith element is the price of a given stock on dayi.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like(ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]

Solution 1:

class Solution {public:    int maxProfit(vector<int>& prices) {        int n = prices.size();        if (n < 2)        {            return 0;        }        int buf[n];        buf[0] = 0;        for (int i = 1; i < n; i++)        {            buf[i] = buf[i-1];            for (int j = 0; j < i; j++)            {                int temp = 0;                if (prices[i] > prices[j])                {                    temp += prices[i]-prices[j];                }                if (j-2 >= 0)                {                    temp += buf[j-2];                }                buf[i] = max(buf[i], temp);            }        }        return buf[n-1];    }};

Solution 2:

int maxProfit(vector<int>& p) {    if (p.size() < 2)        return 0;    int i, sz = p.size();    int ret = 0;    vector<int> buy(sz, 0);    vector<int> sell(sz, 0);    buy[0] = -p[0];    for (i = 1; i < sz; ++i)    {        sell[i] = max(buy[i - 1] + p[i], sell[i - 1] - p[i - 1] + p[i]);        if (ret < sell[i]) //record the max sell[i]            ret = sell[i];        if (1 == i)            buy[i] = buy[0] + p[0] - p[1];        else            buy[i] = max(sell[i - 2] - p[i], buy[i - 1] + p[i - 1] - p[i]);    }    return ret;}


0 0
原创粉丝点击