LeetCode 123 -- Best Time to Buy and Sell Stock III

来源:互联网 发布:linux 搭建cdn 编辑:程序博客网 时间:2024/05/19 19:41

LeetCode 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 dayi.

Design an algorithm to find the maximum profit. You may complete at mosttwo transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


answer:限定两次交易,求两次交易最大的利润。继续运用动态规划。给定一个点,求该点之前的一次交易赚取的最大利润和该点之后赚取的最大的利润。所以两次一前一后遍历。

取最大值。

<span style="font-size:14px;">public class Solution {    public int maxProfit(int[] prices) {        if(prices.length == 0) return 0;        int res = 0 ;        int n = prices.length;                //正向遍历,opt[i]为0到i区间最大的利润        int[] opt = new int[n];        opt[0] = 0;        int low = prices[0];        int curAns = 0;        for(int i = 1; i < n ; i++){            if(prices[i] < low) low = prices[i];            else if(curAns < (prices[i] - low)){                curAns = (prices[i] - low);            }            opt[i] = curAns;        }        //反向遍历,revopt[i]为i到n的最大profit;        int[] revopt = new  int [n];        revopt[n-1] = 0;        int high = prices[n-1];        int curAns1 = 0;        for(int i = (n-2); i >= 0; i--){            if(prices[i] > high) high = prices[i];            else if(curAns1 < (high - prices[i])){                curAns1 = (high - prices[i]);            }            revopt[i] = curAns1;        }        //正反结合        for(int i = 0; i < n; i++){            if(res < (opt[i] + revopt[i])){                res = (opt[i] + revopt[i]);            }        }        return res;    }}</span>


0 0
原创粉丝点击