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.
class Solution {
public:int maxProfit(vector<int> &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int solution = 0;
int minPrice = INT_MAX;
int length = prices.size();
for (int i=0;i<length;++i){
if (prices[i]<minPrice)
minPrice = prices[i];
if (prices[i]-minPrice>solution)
solution = prices[i]-minPrice;
}
return solution;
}
};
本文介绍了一种寻找股票买卖最佳时机以实现最大利润的算法。该算法通过一次遍历股票价格数组来确定最低买入价及随后的最佳卖出时机,从而计算出最大收益。
679

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



