LeetCode 188 Best Time to Buy and Sell Stock IV

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.

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


题目:最佳时间买入卖出股票:你有一个数组保存了股票在第i天的价钱,现在你最多进行K次买卖,但同一时间你手上只能保持一个股票,如何赚的最多?

分析:使用动态规划。local[j]和global[j]表示到第i天,进行j次交易可获取的最大利润。local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); 当到第i天时候,手上若不持有股票,所以第i天买股票,或者不买股票,如果diff = prices[i + 1] - prices[i]>0的时候,就买股票,因为可以赚钱,如果小于0就不买,因为赔钱,此时global[j - 1] + Math.max(diff, 0),这个就是i天不持股票的情况(相当于i-1天的时候股票抛掉),因为我们算得是进行j次交易嘛,第i天还要买一次所以是global[j - 1] + Math.max(diff, 0)。如果第i天手上继续持有以前买的股票,而且也是进行j次交易,等于是第i天前已经进行过的j次交易的最大值,继续持有,不卖,所以是local[j] + diff。

	public int maxProfit(int k, int[] prices) {
		if (prices.length < 2 || k <= 0)
			return 0;
		//纯粹for pass leetcode online judge,因为k == 1000000000时会内存溢出
		//pass leetcode online judge (can be ignored)
		if (k > prices.length / 3) {//可以买卖不限次数
			int res = 0;
			for (int i = 1; i < prices.length; i++) {
				int profit = prices[i] - prices[i - 1];
				if (profit > 0) res += profit;
			}
			return res;
		}
		
		int[] local = new int[k + 1], global = new int[k + 1];
		for (int i = 0; i < prices.length - 1; i++) {
			int diff = prices[i + 1] - prices[i];
			for (int j = k; j >= 1; j--) {
				local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
				global[j] = Math.max(local[j], global[j]);
			}
		}

		return global[k];
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值