Best Time to Buy and Sell Stock IV
2015.4.17 05:27
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:
The "Best Time to Buy and Sell Stock" series has been appearing in several version. Apparently this one is about dynamic programming.
At first I was a bit confused about the definition of "transaction" in the problem desription.
It was one "buy" or one "sell" that is defined as a "transaction", not one buy and one sell.
Thus here comes the typical two-demensional DP. Please see the code below, notice that the key idea lies in the local optimal and global optimal.
I haven't understood the algorithm well enough, though. Yet to think about it.
One thing is for sure: when k is greater than n, this problem is simplified to a greedy version.
Accepted code:
1 // Yet to grasp the mechanism here... DP wasn't easy. 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 6 class Solution { 7 public: 8 int maxProfit(int k, vector<int> &prices) { 9 int n = prices.size(); 10 11 if (k >= n) { 12 return easyMaxProfit(prices); 13 } 14 15 int i, j; 16 vector<int> local, global; 17 18 local.resize(n + 1, 0); 19 global.resize(n + 1, 0); 20 int diff; 21 for (i = 1; i < n; ++i) { 22 diff = prices[i] - prices[i - 1]; 23 for (j = k; j >= 1; --j) { 24 local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff); 25 global[j] = max(global[j], local[j]); 26 } 27 } 28 return global[k]; 29 } 30 private: 31 int easyMaxProfit(vector<int> &prices) { 32 int res; 33 int i, len = prices.size(); 34 35 res = 0; 36 for(i = 0; i < len - 1; ++i){ 37 if(prices[i] < prices[i + 1]){ 38 res += prices[i + 1] - prices[i]; 39 } 40 } 41 42 return res; 43 } 44 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)