3月17日报-所以我放弃了算法(简简单简单单贪心)
- 没学会动态规划,看不进去了,明天一定
- 补充一道贪心 + 前缀和 的题到 313 日报
- 爬去继续看 JavaWeb 了
买卖股票最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
思路解析
本题是[[前缀和#最大子数组和]]的前置题目
本题作为 DP 的引入 (其实是贪心算法) 在遍历完 prices 后,我们需要进行接下来的步骤
- 更新前 i 天的最低价格,获取最低花费成本的
cost - 更新前 i 天的最高利润
profit
代码实现
class Solution {
public int maxProfit(int[] prices) {
int cost = Integer.MAX_VALUE, profit = 0;
for (int price : prices) {
cost = Math.min(cost, price);
profit = Math.max(profit, price - cost);
}
return profit;
}
}