[LeetCode]Best Time to Buy and Sell Stock IV

本文介绍了一种算法,用于寻找股票买卖的最佳时机,允许最多进行k次交易,并确保每次卖出后才能再次购买。通过两个递推公式实现了这一目标,详细展示了如何通过一系列交易最大化利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 k transactions.

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

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

这题难度明显增大。是Best Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock III两道题的结合。

参考博文,主要是两个递推公式。

1 local[j] = max(local[j] + diff, global[j - 1] + max(diff, 0));
2 global[j] = max(global[j], local[j]);
 1 class Solution {
 2 public:
 3     int maxProfit(int k, vector<int>& prices) {
 4         int result;
 5         int total_times=0;
 6         int profit_max = 0;
 7         for(int i=1;i<prices.size();i++)
 8         {
 9             int diff = prices[i]-prices[i-1];
10             if(diff>0)
11             {
12                 profit_max +=diff;
13                 if(((i<prices.size()-1)&&(prices[i+1]-prices[i]<=0))||(i==prices.size()-1))
14                 {
15                     total_times++;
16                 }
17             }
18         }
19         if(k>=total_times) return profit_max;
20         vector<int> local(k + 1, 0);
21         vector<int> global(k + 1, 0);
22         for(int i = 1; i < prices.size(); i++) 
23         {
24             int diff = prices[i] - prices[i - 1];
25             for(int j = k; j >= 1; j--) {
26                 local[j] = max(local[j] + diff, global[j - 1] + max(diff, 0));
27                 global[j] = max(global[j], local[j]);
28             }
29         }
30         return global[k];
31     }
32 };

 

转载于:https://www.cnblogs.com/Sean-le/p/4782281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值