【力扣 买卖股票的最佳时机 Java/Python】
题目:
思路:
维护一个历史最低价,在遍历的时候,用当前价格-最低价 计算利润
不断更新最大的利润。
图解:
Java版本
class Solution {public int maxProfit(int[] prices) {int minPrice = Integer.MAX_VALUE;int maxProfit = 0;for (int price : prices) {minPrice = Math.min(price,minPrice);maxProfit = Math.max(maxProfit, (price - minPrice));}return maxProfit;}
}
python版本:
class Solution(object):def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""minPrice = float('inf') # 无穷大infinitymaxProfit = 0for price in prices:minPrice = min(minPrice,price)maxProfit = max(maxProfit, (price - minPrice))return maxProfit