假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
class Solution {
public:
/**
*
* @param prices int整型vector
* @return int整型
*/
int maxProfit(vector<int>& prices) {
// write code here
int lowest = prices[0];
int max_profit = 0;
// 确保最低买入,和利润最大
for(int i = 1; i < prices.size(); i++){
// 保持最低
if(prices[i] < lowest){
lowest = prices[i];
}
else{
// 保证最大
max_profit = max(max_profit, prices[i] - lowest);
}
}
return max_profit;
}
};