123. Best Time to Buy and Sell Stock III ~~

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).

这道题要求我们最多做两笔交易,求其最大利润。此题是DP题目,需要写出状态方程,即profit = transaction(1)+transaction(2)=sell(1)-buy(1)+sell(2)-buy(2)。代码如下:

public class Solution {

    public int maxProfit(int[] prices) {

        int buy1 = Integer.MIN_VALUE;

        int buy2 = Integer.MIN_VALUE;

        int sell1 = 0;

        int sell2 = 0;

        for(int i=0;i<prices.length;i++){

            buy1 = Math.max(buy1,-prices[i]);

            sell1 = Math.max(sell1,prices[i]+buy1);

            buy2 = Math.max(buy2,sell1-prices[i]);

            sell2 = Math.max(sell2,buy2+prices[i]);

        }

        return sell2;

    }

}

原文地址:https://www.cnblogs.com/codeskiller/p/6358634.html