随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 };
复制代码

 

 posted on   zhuli19901106  阅读(329)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示