剑指 Offer 63. 股票的最大利润
思路#
方法一:暴力法#
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int n = (int)prices.size(), ans = 0; 5 for (int i = 0; i < n; ++i){ 6 for (int j = i + 1; j < n; ++j) { 7 ans = max(ans, prices[j] - prices[i]); 8 } 9 } 10 return ans; 11 } 12 };
方法二:动态规划#
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 if(prices.size() < 2) //这种情况无法交易 5 return 0; 6 7 vector<int> dp(prices.size(), 0); 8 int minPrice = prices[0]; 9 dp[0] = 0; 10 11 for(int i = 1; i < prices.size(); ++i) { 12 if(prices[i] < minPrice) 13 minPrice = prices[i]; 14 15 dp[i] = max(dp[i-1], prices[i] - minPrice); 16 } 17 18 return dp[prices.size()-1]; 19 } 20 }
复杂度分析#
时间复杂度:O(n)
空间复杂度:O(n)
空间优化#
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 if(prices.size() < 2) 5 return 0; 6 7 int minPrice = prices[0]; 8 int profit = 0; 9 10 for(int i = 1; i < prices.size(); ++i) { 11 if(prices[i] < minPrice) 12 minPrice = prices[i]; 13 14 profit = max(profit, prices[i] - minPrice); 15 } 16 17 return profit; 18 } 19 };
复杂度分析#
时间复杂度:O(n)
空间复杂度:O(1)
分类:
剑指Offer(第2版)
标签:
动态规划
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南