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;
}
}
本文介绍了如何使用动态规划方法解决一个简单的编程问题,计算给定股票价格数组中,通过一次买入和卖出操作获取的最大利润。代码展示了如何初始化最小值和利润变量,遍历价格数组并更新它们。
396

被折叠的 条评论
为什么被折叠?



