方法一:暴力法
两次for循环,一个一个比较,找出最大利润
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int len = prices.size();
int max_profit = 0;
for (int i = 0; i < len; ++i)
{
for (int j = i + 1; j < len; ++j)
{
max_profit = max(max_profit, prices[j] - prices[i]);
}
}
return max_profit;
}
};
int main()
{
Solution A;
vector<int> ve{ 7,1,5,3,6,4 };
cout << A.maxProfit(std::ref(ve)) << endl;
return 0;
}
时间复杂度:O(n^2),循环运行 n(n+1)/2 次
空间复杂度:O(1),只使用了常数个变量
方法二:一次遍历
记录历史最低价格 min_price,我们就可以假设自己的股票是在那天买的那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - min_price
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int len = prices.size();
int max_profit = 0;
int min_price = INT_MAX;
for (auto x:prices)
{
max_profit = max(max_profit, x - min_price);
min_price = min(min_price, x);
}
return max_profit;
}
};
int main()
{
Solution A;
vector<int> ve{ 7,1,5,3,6,4 };
cout << A.maxProfit(std::ref(ve)) << endl;
return 0;
}
时间复杂度:O(n),只需要遍历一次
空间复杂度:O(1),只使用了常数个变量