思路
方法一:暴力法
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)