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;
}
};