# LeetCode Best Time to Buy and Sell Stock

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.

Example 1:

```Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
```

Example 2:

```Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.```

```class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2)return 0;
vector<int> diff(prices.size() - 1);
for (int i = 1; i < prices.size(); ++i) {
diff[i - 1] = prices[i] - prices[i - 1];
}
vector<int> dp(diff.size());
int ans = 0;
for (int i = 0; i < diff.size(); ++i) {
if (i == 0 || dp[i - 1] < 0)dp[i] = diff[i];
else dp[i] = dp[i - 1] + diff[i];
ans = max(ans, dp[i]);
}
return ans;
}
};
```

```class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2)return 0;
vector<int> dp(prices.size());
int min_so_far = prices[0], ans = 0;
for (int i = 1; i < prices.size(); ++i) {
dp[i] = prices[i] - min_so_far;
min_so_far = min(min_so_far, prices[i]);
ans = max(ans, dp[i]);
}
return ans;
}
};
```

```class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n < 2)return 0;
vector<int> minprice(n), maxprice(n);
int ans = 0;
for (int i = 0; i < n; ++i) {
minprice[i] = (i == 0 ? prices[0] : min(minprice[i - 1], prices[i]));
maxprice[n - i - 1] = (i == 0 ? prices[n - 1] : max(maxprice[n - i], prices[n - i - 1]));
}
for (int i = 0; i < n; ++i) {
ans = max(ans, maxprice[i] - minprice[i]);
}
return ans;
}
};
```