123. Best Time to Buy and Sell Stock III

来源:互联网 发布:mysql 重启服务 编辑:程序博客网 时间:2024/06/08 16:25
  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. 解决思路
    和第121题一样的,只是变成了两次操作而已。用两个buy变量和两个sell变量实现动态规划即可。(注意,第二次buy的状态转移方程为buy2 = max(buy2,-prices[i]+sell1))

  3. 代码

class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.size() == 0)            return 0;        int buy1 = INT_MIN ,sell1 = INT_MIN , buy2 = INT_MIN, sell2 = INT_MIN;        for (int i = 0 ; i < prices.size(); ++i) {            buy1 = max(buy1,-prices[i]);            sell1 = max(sell1,prices[i]+buy1);            buy2 = max(buy2,sell1-prices[i]);            sell2 = max(sell2,buy2+prices[i]);        }        return sell2;    }};
0 0
原创粉丝点击