Python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
min_price = prices[0]
for i in range(1, len(prices)):
max_profit = max(max_profit, prices[i] - min_price)
min_price = min(min_price, prices[i])
return max_profit
Java
法1:DP
简单题目
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 1) {
return 0;
}
int min = prices[0], profit = 0;
for (int i = 1; i < prices.length; ++i) {
min = Math.min(min, prices[i - 1]);
profit = Math.max(profit, prices[i] - min);
}
return profit;
}
}