[leetcode] Best Time to Buy and Sell Stock 1

Description:

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.

Tags: array, dynamic programming

1. 如果当前天的股票价格是已知域的最高价，更新max变量；

2. 如果我在当前天买，在已知域的最高价卖，max – prices[i] > profit。则更新profit变量。

C++代码：

```class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
int max, profit;
if (n <= 1){
return 0;
}
max = *(prices.end() - 1);
profit = 0;
for (int i = n - 1; i >=0; i--){
if (prices[i] > max){
max = prices[i];
}
else if(prices[i] < max - profit){
profit = max - prices[i];
}
}
return profit;
}
};```

```class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if len(prices) <= 1:
return 0
min = prices[0]
profit = 0
for p in prices[1:]:
if p < min:
min = p
elif p - min > profit:
profit = p - min
return profit```

This site uses Akismet to reduce spam. Learn how your comment data is processed.