# 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.

```c++
class Solution {
public:
int maxProfit(vector &prices) {
if(prices.size() <= 1) {
return 0;
}

int minP = prices[0];

int profit = prices[1] - prices[0];

for(int i = 2; i < prices.size(); i++) {
minP = min(prices[i - 1], minP);
profit = max(profit, prices[i] - minP);
}

if(profit < 0) {
return 0;
}

return profit;
}
};
```

# Best Time to Buy and Sell Stock II

> Say you have an array for which the ith element is the price of a given stock on day i.

> Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

```c++
class Solution {
public:
int maxProfit(vector &prices) {
int len = (int)prices.size();
if(len <= 1) {
return 0;
}

int sum = 0;
for(int i = 1; i < len; i++) {
if(prices[i] - prices[i - 1] > 0) {
sum += prices[i] - prices[i - 1];
}
}

return sum;
}
};
```

# Best Time to Buy and Sell Stock III

> Say you have an array for which the ith element is the price of a given stock on day i.

> Design an algorithm to find the maximum profit. You may complete at most two transactions.

> Note:
> You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

```c++
class Solution {
public:
int maxProfit(vector &prices) {
int len = (int)prices.size();
if(len <= 1) {
return 0;
}

vector profits;
profits.resize(len);

//首先我们正向遍历得到每天一次交易的最大收益
//并保存到profits里面
int minP = prices[0];
int sum = numeric_limits::min();
for(int i = 1; i < len; i++) {
minP = min(minP, prices[i - 1]);
profits[i] = max(sum, prices[i] - minP);

sum = profits[i];
}

int maxP = prices[len - 1];
int sum2 = numeric_limits::min();

//逆向遍历
for(int i = len - 2; i >= 0; i--) {
maxP = max(maxP, prices[i + 1]);
sum2 = max(sum2, maxP - prices[i]);

if(sum2 > 0) {
//这里我们直接将其加入profits里面，
//不需要额外保存
profits[i] = profits[i] + sum2;
sum = max(sum, profits[i]);
}
}

return sum > 0 ? sum : 0;
}
};
```