# [LeetCode] Best Time to Buy and Sell Stock 买卖股票的最佳时间

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.

[10,5],2

## 1.一次交易卖买

class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, buy = INT_MAX;
for (int price : prices) {
res = max(res, price - buy);
}
return res;
}
};

## 2. 无限次交易买卖，必须是一次交易结束了，再进行下一次交易，

class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, n = prices.size();
for (int i = 0; i < n - 1; ++i) {
//res+= prices[i] - prices[i-1] >0 ? prices[i] - prices[i-1] :0 ;
if (prices[i] < prices[i + 1])
{
res += prices[i + 1] - prices[i];
}
}
return res;
}
};

## 3.最多允许两次交易，但必须是一次交易结束了，再进行下一次交易

class Solution {
public:
/**
* 计算你能获得的最大收益
*
* @param prices Prices[i]即第i天的股价
* @return 整型
*/
int calculateMax(vector<int> prices) {
int len = prices.size();
vector<int> leftmax(n);
vector<int> rightmax(n);

//正序遍历
int primin = prices[0];
leftmax[0] = 0;
for(int i=1;i<len;++i){
primin = min(primin, prices[i]);
leftmax[i] = max(leftmax[i-1], prices[i] - primin);
}

//后序遍历
int primax = prices[len-1];
rightmax[len-1] = 0;
for(int i=len-2;i>=0;--i){
primax = max(primax, prices[i]);
rightmax[i] = max(rightmax[i+1], primax - prices[i]);
}

int pmax = 0;
for(int i=0;i<len;++i)
pmax = max(pmax, leftmax[i] + rightmax[i]);
return pmax;

}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120