[LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 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).
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.
123. Best Time to Buy and Sell Stock III 这题是最多能交易2次,而这题是最多k次。
要用动态规划Dynamic programming来解,需要两个递推公式来分别更新两个变量local和global。定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为:
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
global[i][j] = max(local[i][j], global[i - 1][j])
Java:
public int maxProfit(int k, int[] prices) {
int len = prices.length;
if (k >= len / 2) return quickSolve(prices); int[][] t = new int[k + 1][len];
for (int i = 1; i <= k; i++) {
int tmpMax = -prices[0];
for (int j = 1; j < len; j++) {
t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax);
tmpMax = Math.max(tmpMax, t[i - 1][j - 1] - prices[j]);
}
}
return t[k][len - 1];
} private int quickSolve(int[] prices) {
int len = prices.length, profit = 0;
for (int i = 1; i < len; i++)
// as long as there is a price gap, we gain a profit.
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
return profit;
}
Python:
class Solution(object):
# @return an integer as the maximum profit
def maxProfit(self, k, prices):
if k >= len(prices) / 2:
return self.maxAtMostNPairsProfit(prices) return self.maxAtMostKPairsProfit(prices, k) def maxAtMostNPairsProfit(self, prices):
profit = 0
for i in xrange(len(prices) - 1):
profit += max(0, prices[i + 1] - prices[i])
return profit def maxAtMostKPairsProfit(self, prices, k):
max_buy = [float("-inf") for _ in xrange(k + 1)]
max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)):
for j in xrange(1, min(k, i/2+1) + 1):
max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i])
max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k]
C++:
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
if (prices.empty()) return 0;
if (k >= prices.size()) return solveMaxProfit(prices);
int g[k + 1] = {0};
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[k];
}
int solveMaxProfit(vector<int> &prices) {
int res = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] - prices[i - 1] > 0) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
};
类似题目:
[LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
[LeetCode] 122. Best Time to Buy and Sell Stock II 买卖股票的最佳时间 II
[LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown 买卖股票的最佳时间有冷却期
All LeetCode Questions List 题目汇总
[LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV的更多相关文章
- [LeetCode] 122. Best Time to Buy and Sell Stock II 买卖股票的最佳时间 II
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- LeetCode 121. Best Time to Buy and Sell Stock (买卖股票的最好时机)
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] 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 al ...
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
Say you have an array for which the i th element is the price of a given stock on day i. Design an a ...
- LeetCode 188. Best Time to Buy and Sell Stock IV (stock problem)
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- 122 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II
假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格.设计一个算法来找到最大的利润.你可以完成尽可能多的交易(多次买卖股票).然而,你不能同时参与多个交易(你必须在再次购买前出售股票) ...
随机推荐
- Codeforces Round #560 (Div. 3) Microtransactions
Codeforces Round #560 (Div. 3) F2. Microtransactions (hard version) 题意: 现在有一个人他每天早上获得1块钱,现在有\(n\)种商品 ...
- Linux系统文件/etc/fstab
挂载可以使用命令或者修改系统文件两种方式,第一种方式使用mount命令挂载文件系统可以立即生效并使用,但计算机重启后无效.另一种方式需要修改系统文件/etc/fstab,这种方式挂载的文件系统在计算机 ...
- Python爬虫爬企查查数据
因为制作B2b网站需要,需要入库企业信息数据.所以目光锁定企查查数据,废话不多说,开干! #-*- coding-8 -*- import requests import lxml import sy ...
- git添加doc文件维护
原文地址:https://www.cnblogs.com/yezuhui/p/6853271.html 说明: git 一般只能对纯文本文件进行版本控制,但是如果有其他中间转化软件的协助,就可以对任意 ...
- SignalR入门一、通过 SignalR 2 进行实时聊天
一:什么是signalR Asp.net SignalR是微软为实现实时通信的一个类库.一般情况下,signalR会使用JavaScript的长轮询(long polling)的方式来实现客户端和服务 ...
- linux中如何升级Python
一.使用wget 下载Python 安装包 我是在虚拟中当中安装的: wget http://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz 报错: ...
- SQL SERVER错误:已超过了锁请求超时时段。
问题:远程连接数据库,无法打开视图,报错:SQL SERVER错误:已超过了锁请求超时时段. (Microsoft SQL Server,错误: 1222) 执行语句获取进程id select * f ...
- NVIDIA vGPU License服务器搭建详解
当配置有vGPU虚拟机发起License授权请求,授权服务器会根据License中所包含的GRID License版本,加载不同的vGPU驱动(普通驱动和专业Quodra卡驱动).目前vPC和vApp ...
- Huawei Honorcup Marathon 2 垫底记
先放链接: Huawei Honorcup Marathon 2 在 CF 上面看到这个比赛,就去玩了一下. 一开始的做法时先选一个块,然后不断看其它的每一个块拼在哪里的误差最小,然后拼上去.误差函数 ...
- 2016级移动应用开发在线测试13-Location、Sensor & Network
有趣有内涵的文章第一时间送达! 喝酒I创作I分享 生活中总有些东西值得分享 @醉翁猫咪 1. 充分利用智能手机的GPS定位信息,创造了O2O的商业模式,打通了线上与线下的信息流和商流,极大地推动了移 ...