美文网首页
Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

作者: Frank_Kivi | 来源:发表于2018-06-28 09:27 被阅读11次

https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-with-cooldown/description

public class Solution {
    /**
     * @param prices: a list of integers
     * @return: return a integer
     */
    public int maxProfit(int[] prices) {
        // write your code here
        int[] buy = new int[prices.length];
//        当天持有股票
        int[] sell = new int[prices.length];
//        当天没有股票
        buy[0] = -prices[0];
        sell[0] = 0;
        buy[1] = Math.max(buy[0], -prices[1]);
        sell[1] = Math.max(sell[0], buy[0] + prices[1]);
        for (int i = 2; i < prices.length; i++) {
            int price = prices[i];
            buy[i] = Math.max(buy[i - 1], sell[i - 2] - price);
            sell[i] = Math.max(sell[i - 1], buy[i - 1] + price);
        }
        return sell[sell.length - 1];
    }
}

相关文章

网友评论

      本文标题:Best Time to Buy and Sell Stock

      本文链接:https://www.haomeiwen.com/subject/ojnwyftx.html