zoukankan      html  css  js  c++  java
  • 123. Best Time to Buy and Sell Stock III--Hard

    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:

    Input: [3,3,5,0,0,3,1,4]
    Output: 6
    Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
    Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
    Example 2:

    Input: [1,2,3,4,5]
    Output: 4
    Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
    engaging multiple transactions at the same time. You must sell before buying again.
    Example 3:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.

    1.思考

    • 下面有两种方法进行解决:
    • 方法1:
      (1) buy1 is you buy it day x cost price;
      (2) sell1 is the profit you get sell-cost price of 1;
      (3) buy2 is you buy it on day z with the profit you got from selling the first stock you bought;
      (4) sell2 is the profit of selling the second stock, you already used the profit of first stock to buy second. Hence we only need to return sell2.
    • 方法2:0 - 1 buy, 1 - 1 buy 1 sell, 2 - 2 buy 1 sell, 3 - 2 buy 2 sell.

    2.实现

    class Solution {
    public:
    	int maxProfit_Solution1(vector<int>& prices) {
    		int len = prices.size();
    		if (len <= 1)
    			return 0;
    
    		int buy1 = INT_MAX;
    		int sell1 = 0;
    		int buy2 = INT_MAX;
    		int sell2 = 0;
    
    		for (int i = 0; i<len; i++)
    		{
    			int p = prices[i];
    			buy1 = min(buy1, p);
    			sell1 = max(sell1, p - buy1);
    			buy2 = min(buy2, p - sell1);
    			sell2 = max(sell2, p - buy2);
    		}
    
    		return sell2;		
    	}
    
    	int maxProfit_Solution2(vector<int>& prices) {
    		int n = prices.size();
    		int dp[2][4]; // 0 - 1 buy, 1 - 1 buy 1 sell, 2 - 2 buy 1 sell, 3 - 2 buy 2 sell
    		for (int i = 0; i<4; ++i)
    			dp[0][i] = INT_MIN / 2;
    
    		for (int i = 0; i<n; ++i){
    			dp[1][0] = max(dp[0][0], -prices[i]);
    			dp[1][1] = max(dp[0][1], dp[0][0] + prices[i]);
    			dp[1][2] = max(dp[0][2], dp[0][1] - prices[i]);
    			dp[1][3] = max(dp[0][3], dp[0][2] + prices[i]);
    			swap(dp[0], dp[1]);
    		}
    
    		return max(0, max(dp[0][1], dp[0][3]));
    	}
    };
    
  • 相关阅读:
    No.2 对象与内存控制(内存分配)
    No.1 数组与内存控制
    Json解析 在VS中
    MVC 搜索防止点击其他按钮
    执行多个lanmada表达式查询
    删除重复数据
    分页
    DataSet与二进制文件和XML文件
    关于时间的转换
    转换人民币大小金额
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/11283586.html
Copyright © 2011-2022 走看看