原题链接:121.Best Time to Buy and Sell Stock
【思路】
本题考查动态规划。复杂度为n(O),在遍历过程中记录最小值min。结果 result 只取决于 result 与 prices[i] - min 中的较大值:
public int maxProfit(int[] prices) {
int result = 0, min = 0x7fff_ffff;
for (int price : prices)
if (price < min) min = price;
else result = Math.max(result, price - min);
return result;
}
198 / 198
test cases passed. Runtime: 2 ms Your runtime beats 60.20% of javasubmissions.
本文介绍了一种解决股票买卖最佳时机问题的高效算法。通过动态规划的方法,在O(n)的时间复杂度内找到最大利润,关键在于遍历过程中记录最小买入价格,并据此计算当前可能的最大收益。
2275

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



