[LeetCode] Best Time to Buy and Sell Stock III
Personally, this is a relatively difficult DP problem. This link posts a typical DP solution to it. You may need some time to get how it works.
The code is rewritten as follows.
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int n = prices.size(), num = 2; 5 if (n <= 1) return 0; 6 vector<vector<int> > dp(num + 1, vector<int>(n, 0)); 7 for (int k = 1; k <= num; k++) { 8 int temp = dp[k - 1][0] - prices[0]; 9 for (int i = 1; i < n; i++) { 10 dp[k][i] = max(dp[k][i - 1], prices[i] + temp); 11 temp = max(temp, dp[k - 1][i] - prices[i]); 12 } 13 } 14 return dp[num][n - 1]; 15 } 16 };
Personally, I prefer this solution, which is much easier to understand. The code is also rewritten as follows.
class Solution { public: int maxProfit(vector<int>& prices) { int states[2][4] = {INT_MIN, 0, INT_MIN, 0}; int n = prices.size(), cur = 0, next = 1; for (int i = 0; i < n; i++) { states[next][0] = max(states[cur][0], -prices[i]); states[next][1] = max(states[cur][1], states[cur][0] + prices[i]); states[next][2] = max(states[cur][2], states[cur][1] - prices[i]); states[next][3] = max(states[cur][3], states[cur][2] + prices[i]); swap(cur, next); } return max(states[cur][1], states[cur][3]); } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档