买卖股票的最佳时机

假设有一个数组,它的第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
int MaxProfit = 0;
int length = prices.size();
if ( length < 2 )
return 0;
else{
int lowprice = prices[0];
for (int i = 1;i<length; i++){
if(prices[i] < lowprice )
lowprice = prices[i];
else
MaxProfit = (prices[i]-lowprice) > MaxProfit ? prices[i]-lowprice:MaxProfit;
}
return MaxProfit;
}
}
};code

 

买卖股票时,先买后卖,所以,当买入的价格高于卖出的价格,即为亏损。买入的价格低于卖出的价格,为盈利。遍历数组,找到最低的买入价格,并记录差价,直到找到最大利润。it

相关文章
相关标签/搜索