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) {
if(prices.size()<=1) return 0;
int max = prices[0],min = prices[0],r_min = prices[0];
for(int i=1;i<prices.size();++i){
//当前值比最大的大,变更最大值
if(prices[i]>max){
max = prices[i];
}
//当前能取得的最大利润大,更新区间
if((prices[i]-r_min)>(max-min)){
min = r_min;
max = prices[i];
}
//更新实际最小值
if(prices[i]< r_min){
r_min = prices[i];
}
}
return max - min;
}
};