您的位置:首页 > 其它

Best Time to Buy and Sell Stock

2015-11-29 11:18 218 查看
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>& diff,int diffSize){
int curMax=0;
int res = 0;
for(int i=0;i<diffSize;i++){
if(i==0){
curMax = diff[i];
res = diff[i];
}else{
curMax = max(curMax+diff[i],diff[i]);
res = max(res,curMax);
}
}
return res;
}
int maxProfit(vector<int>& prices) {
int pricesSize = prices.size();
vector<int> diff(pricesSize,0);
for(int i=1;i<pricesSize;i++){
diff[i] = prices[i]-prices[i-1];
}
return maxProfit(diff,pricesSize);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: