121.買賣股票的最佳時機
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
如果你最多隻允許完成一筆交易(即買入和賣出一支股票一次),設計一個算法來計算你所能獲取的最大利潤。
注意:你不能在買入股票前賣出股票。
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.
solution:此題與上一道題的不同之處是最多隻允許進行一次買賣
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# (1)暴力法,也是最容易想到的
# maxResult = 0
# for i in range(len(prices)):
# for j in range(len(prices)-i-1):
# if(prices[j+i+1]-prices[i] > maxResult):
# maxResult = prices[j+i+1]-prices[i]
# return maxResult
# (2)遍歷一次,使用minP來記錄交易中的最低價格,遍歷找到最大利潤值
minP = sys.maxint # python3中用 sys.maxsize來獲取最大整數
maxP = 0
for i in range(len(prices)):
if (prices[i] < minP):
minP = prices[i]
elif(prices[i] - minP > maxP):
maxP = prices[i] - minP
return (0 if maxP<0 else maxP)
上面爲一年前用Python寫的,今天用c++重新寫一次
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty())
return 0;
int minP = prices[0]; // 最小价格
int maxP = 0; // 最大利潤
for(auto i:prices){
if(i < minP)
minP = i;
else if(i-minP > maxP)
maxP = i - minP;
}
return maxP;
}
};