码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】

时间:2015-06-06 22:05:00      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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 k transactions.

解题思路:

本题是Best Time to Buy and Sell Stock系列最难的一道,需要用到dp,JAVA实现如下:

 

    public int maxProfit(int k, int[] prices) {
        if (k == 0 || prices.length < 2)
            return 0;
        if (k > prices.length / 2) {
            int maxProfitII = 0;
            for (int i = 1; i < prices.length; ++i)
                if (prices[i] > prices[i - 1])
                	maxProfitII += prices[i] - prices[i - 1];
            return maxProfitII;
        }
        int[] buy=new int[k];
        int[] sell=new int[k];
        for(int i=0;i<buy.length;i++)
        	buy[i]=Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++)
            for (int j = k - 1; j >= 0; j--) {
                sell[j] = Math.max(sell[j], buy[j] + prices[i]);
                if (j == 0)
                    buy[j] = Math.max(buy[j], -prices[i]);
                else
                    buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]);
            }
        return sell[k - 1];
    }

 

Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4557321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!