给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
#include <vector>
#include <algorithm>
using namespace std;
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n <= 1) return 0;
int maxProfit = 0;
int minPrice = prices[0];
for (int i = 1; i < n; ++i) {
maxProfit = max(maxProfit, prices[i] - minPrice);
minPrice = min(minPrice, prices[i]);
}
return maxProfit;
}
int main() {
vector<int> prices = {7, 1, 5, 3, 6, 4};
int max_profit = maxProfit(prices);
cout << "Maximum profit: " << max_profit << endl;
return 0;
}
时间复杂度分析:
遍历数组一次,时间复杂度为 O(n),其中 n 为数组的长度。
空间复杂度分析:
仅使用了常量级别的额外空间,空间复杂度为 O(1)。
该算法的核心思想是维护两个变量:当前最小价格(minPrice)和当前最大利润(maxProfit)。在遍历数组时,更新最小价格和计算当前价格与最小价格的差值,得到当前最大利润。最终返回最大利润即可。