Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
» Solve this problem
记录之前的股票最低值,判断今日的股票值-之前的最低值是否大于最大的利润。
更新最低值。
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() == 0) {
return 0;
}
int min = prices[0], profit = 0;
for (int i = 1; i < prices.size(); i++) {
profit = prices[i] - min > profit ? prices[i] - min : profit;
min = prices[i] < min ? prices[i] : min;
}
return profit;
}
};
本文介绍了一种解决最大股票交易利润问题的算法,通过跟踪历史最低股价并计算每日差额来确定最大收益。
529

被折叠的 条评论
为什么被折叠?



