买卖股票的最佳时机

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例

给出一个数组样例 [3,2,3,1,2], 返回 1 

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
if(prices.size() == 0){ //时刻注意数组越界
return 0;
}

int max = 0;
int cur = prices[0];
for(int i = 1; i < prices.size(); i++){
if(prices[i] < cur){ //卖掉会亏
cur = prices[i];
}else{ //卖掉能挣
int tmp = prices[i] - cur;
if(tmp > max){
max = tmp;
}
}
}
return max;
}
};

posted @ 2017-03-08 11:53  liuyingxiu  阅读(98)  评论(0)    收藏  举报