leetcode-121

这题使用双指针法

1
2
3
4
5
6
7
8
9
10
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""

max_profit, min_price = 0, float('inf')
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxPro = 0;
int minPrice = INT_MAX;
for(int i = 0; i < prices.size(); i++){
minPrice = min(minPrice, prices[i]);
maxPro = max(maxPro, prices[i] - minPrice);
}
return maxPro;
}
};
1
2
3
4
5
6
7
8
9
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res=0,buyp=INT_MAX;
for(auto i:prices)
(i<buyp)?(buyp=i):(res=max(i-buyp,res));
return res;
}
};

更加简洁的cpp