题目链接
题目(中等)
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖股票一次可能获得的最大利润是多少?例如,一只股票在某些时间节点的价格为{9,11,8,5,7,12,16,14}。如果我们能在价格为5的时候买入并且在价格为16时卖出,则能收获最大的利润11。如果你不能获取任何利润,返回 0。
示例
示例 1:
输入:prices = [3, 6, 2, 9, 8, 5]
输出:7
解释:在第 3 天(芯片价格 = 2)买入,在第 4 天(芯片价格 = 9)卖出,最大利润 = 9 - 2 = 7。
示例 2:
输入:prices = [8, 12, 15, 7, 3, 10]
输出:7
解释:在第 5 天(芯片价格 = 3)买入,在第 6 天(芯片价格 = 10)卖出,最大利润 = 10 - 3 = 7。
提示:
- 0 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
- 注意:本题与 121 题相同:leetcode-cn.com/problems/be…
题解
一次遍历
- 时间复杂度 O(N): 其中 N 为 prices 列表长度,动态规划需遍历 prices 。
- 空间复杂度 O(1): 变量 cost 和 profit 使用常数大小的额外空间。
var maxProfit = function(prices) {
let minprice = Number.MAX_VALUE;
let maxprofit = 0;
for (const price of prices) {
maxprofit = Math.max(price - minprice, maxprofit);
minprice = Math.min(price, minprice);
}
return maxprofit;
};
// 相同的思路
var bestTiming = function(prices) {
let minPrice = prices[0];
let maxProfit = 0;
for(let i = 1; i < prices.length; i++) {
if(prices[i] < minPrice) {
minPrice = prices[i];
} else if(prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
};