题目 只买一次,找到最大收益
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.
解法
想法是很简单的:如果在第i个位置出售,买入价一定要是第i个位置之前的最小值。通过 O(n) 一次遍历可得最大收益。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxGap = 0;
int curMin = prices.size() > 0 ? prices[0] : 0;
for (int i = 1; i < prices.size(); i++) {
maxGap = max(prices[i] - curMin, maxGap); //更新最大值
curMin = min(prices[i], curMin); //更新访问到现在为止的最小值
}
return maxGap;
}
};