LeetCode188 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 ktransactions.

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

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

题源:here;完整实现:here

思路:

参考:here;请注意,文中使用了转移条件的前后关系,成功缩减了内存的申请量。

class Solution {
public:
	int maxProfit(int k, vector<int>& prices) {
		if (prices.empty()) return 0;
		if (k >= prices.size()) return helper(prices);
		vector<int> g(k + 1, 0);
		vector<int> l(k + 1, 0);
		for (int i = 0; i < prices.size() - 1; i++) {
			int diff = prices[i + 1] - prices[i];
			for (int j = k; j >= 1; --j) {
				l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff);
				g[j] = max(g[j], l[j]);
			}
		}
		return g.back();
	}
	int helper(vector<int> &prices) {
		int res = 0;
		for (int i = 1; i < prices.size(); ++i) {
			int tmp = prices[i] - prices[i - 1];
			if (tmp > 0) res += tmp;
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88420902
今日推荐