Leetcode Best Time to Buy and Sell Stock III

来源:互联网 发布:高通编译linux 编辑:程序博客网 时间:2024/06/09 01:15

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


Difficulty: Hard


Solution: DP

public class Solution {    public int maxProfit(int[] prices) {        int len = prices.length;        if(len == 0) return 0;        if(len == 1) return 0;        int[] nodes = new int[len];        int[] nodes_re = new int[len];        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;        for(int i = len - 1; i >= 0; i--){            max = Math.max(max, prices[i]);            if(i < len - 1)                nodes_re[i] = Math.max(nodes_re[i + 1], max - prices[i]);        }                for(int j = 0; j < len; j++){            min = Math.min(min, prices[j]);            if(j > 0)                nodes[j] = Math.max(nodes[j - 1], prices[j] - min);        }                int ans = 0;        for(int i = 0; i < len - 1; i++){            ans = Math.max(ans, nodes[i] + nodes_re[i + 1]);        }        return Math.max(ans, nodes[len - 1]);    }}


0 0