算法1(暴力)
时间复杂度:(O(n^2))
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = INT_MIN;
if (prices.empty()) return 0;
for (int i = 0; i < prices.size(); ++i) {
for (int j = i; j < prices.size(); ++j) {
ans = max(ans, prices[j] - prices[i]);
}
}
return ans;
}
};
算法2(优化)
时间复杂度:(O(n))
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
if (prices.empty()) return 0;
int min_pro = prices[0];
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > prices[i - 1]) {
ans = max(ans, prices[i] - min_pro);
} else {
min_pro = min(min_pro, prices[i]);
}
}
return ans;
}
};