LeetCode Best Time to Buy and Sell Stock IV

Description:

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

Solution:

We may use dp[i][l] to represent that we can get the most money before day i and within k transactions.

So we can easily get the transformation equation:

dp[i][l] = max { dp[i-1][l] , dp[i][l-1], max{ dp[j-1][l-1] + prices[i] - prices[j] } }

We may as well make a little change in this equation:

dp[j-1][l-1] + prices[i] - prices[j] = dp[j-1][l-1] - prices[j] + prices[i]

And we can use one variable to keep the value of { dp[j-1][l-1] - prices[j] }. Just be aware that we need to change the loop of k in the outsider, and the loop of prices inside in order to realize this {dp[j-1][l-1] - prices[j]} variable. So the time complexity will reduce from O(n^2 * k) to O(n*k).

But also pay attention that there are still some test cases that cannot pass, which has a very large k. The solution to this is very simple, every time 2*k >= n, it is obvious that we can add all the adjacent increasing number.

import java.util.*;

public class Solution {

	public int maxProfit(int k, int[] prices) {
		int len = prices.length;
		if (len == 0)
			return 0;
		if (k * 2 >= len) {
			int ans = 0;
			for (int i = 1; i < len; i++)
				if (prices[i] > prices[i - 1])
					ans += prices[i] - prices[i - 1];
			return ans;
		}

		int dp[][] = new int[len][k + 1];

		int temp = 0;
		// max { dp[j-1][k-1] + prices[i] - prices[j] }
		// temp = max dp[j-1][k-1] - prices[j]
		for (int l = 1; l <= k; l++) {
			temp = -prices[0];
			for (int i = 1; i < len; i++) {
				dp[i][l] = Math.max(dp[i - 1][l], dp[i][l - 1]);
				dp[i][l] = Math.max(dp[i][l], prices[i] + temp);
				temp = Math.max(temp, dp[i - 1][l - 1] - prices[i]);
			}
		}

		int max = 0;
		for (int i = 0; i <= k; i++)
			max = Math.max(max, dp[len - 1][i]);
		return max;
	}

	public static void main(String[] args) {
		int arr[] = new int[] { 2, 1, 2, 0, 1 };
		Solution s = new Solution();
		System.out.println(s.maxProfit(2, arr));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值