剑指 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)

 

posted @   拾月凄辰  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· 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代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示
主题色彩