织梦网站程序模板下载地址,住建部四库一平台,物流服务与管理,中展建设股份有限公司网站买卖股票的最佳时机
问题描述
给定一个数组 prices#xff0c;其中 prices[i] 表示第 i 天的股票价格。你只能选择某一天买入股票#xff0c;并选择未来的某一天卖出股票#xff0c;设计一个算法来计算你所能获取的最大利润。 限制条件#xff1a; 只能进行一次交易…买卖股票的最佳时机
问题描述
给定一个数组 prices其中 prices[i] 表示第 i 天的股票价格。你只能选择某一天买入股票并选择未来的某一天卖出股票设计一个算法来计算你所能获取的最大利润。 限制条件 只能进行一次交易也就是说最多只能买入和卖出各一次。买入必须在卖出之前不能在买入之前卖出股票。 目标返回可以获得的最大利润。如果无法获取任何利润返回 0。
示例 示例 1 输入prices [7,1,5,3,6,4]
输出5
解释在第 2 天价格为 1买入在第 5 天价格为 6卖出利润为 6 - 1 5。示例 2 输入prices [7,6,4,3,1]
输出0
解释在这种情况下没有交易完成所以最大利润为 0。解题思路
为了求最大利润我们需要在买入价格最低的时候买入并在之后价格最高的时候卖出。然而由于我们只能遍历一次数组并且需要在买入之后才能卖出因此我们需要一种高效的方法来计算最大利润。
核心思想
维护一个当前为止的最低买入价格 minPrice。计算当前价格与最低买入价格之间的差值即当前可获得的利润 price - minPrice。维护一个最大利润值 maxProfit在遍历过程中更新它。
算法步骤 初始化 minPrice Infinity表示当前遇到的最低价格初始为正无穷大。maxProfit 0表示当前计算的最大利润初始为 0。 遍历价格数组 对于每个价格 price执行以下操作 更新最低价格 如果 price minPrice则更新 minPrice price。 计算当前利润并更新最大利润 计算当前利润 profit price - minPrice。如果 profit maxProfit则更新 maxProfit profit。 返回结果 遍历完成后maxProfit 即为所能获得的最大利润。
代码详解
function maxProfit(prices: number[]): number {let minPrice Infinity; // 初始化最低价格为无穷大let maxProfit 0; // 初始化最大利润为 0for (let price of prices) {if (price minPrice) {minPrice price; // 更新最低价格} else if (price - minPrice maxProfit) {maxProfit price - minPrice; // 更新最大利润}}return maxProfit;
}变量初始化 minPrice用于记录当前为止的最低买入价格。maxProfit用于记录当前为止的最大利润。 遍历数组 for (let price of prices) {...
}更新最低价格 if (price minPrice) {minPrice price;
}如果当前价格比之前记录的最低价格还低更新最低价格。 更新最大利润 else if (price - minPrice maxProfit) {maxProfit price - minPrice;
}如果当前价格与最低价格的差值利润大于之前的最大利润更新最大利润。 返回结果 return maxProfit;返回计算得到的最大利润。
示例演示
以示例 1 为例prices [7,1,5,3,6,4] 初始状态 minPrice InfinitymaxProfit 0 遍历过程 price 7 7 Infinity更新 minPrice 7。没有更新 maxProfit因为 price - minPrice 0。 price 1 1 7更新 minPrice 1。没有更新 maxProfit因为 price - minPrice 0。 price 5 5 1计算利润 5 - 1 4。4 0更新 maxProfit 4。 price 3 3 1计算利润 3 - 1 2。2 4maxProfit 不变。 price 6 6 1计算利润 6 - 1 5。5 4更新 maxProfit 5。 price 4 4 1计算利润 4 - 1 3。3 5maxProfit 不变。 结果 最终 maxProfit 5。
时间和空间复杂度分析 时间复杂度O(n)其中 n 是数组 prices 的长度。我们只需要遍历一次数组。 空间复杂度O(1)只使用了常数级别的额外空间。
边界情况处理 价格单调递减 例如 prices [7,6,4,3,1]在这种情况下无法获得正利润。算法会始终更新 minPrice但 maxProfit 保持为 0。最终返回 0。 只有一个价格 当 prices.length 1 时无法完成交易利润为 0。
测试代码
function testMaxProfit() {const testCases [{ prices: [7, 1, 5, 3, 6, 4], expected: 5 },{ prices: [7, 6, 4, 3, 1], expected: 0 },{ prices: [1, 2], expected: 1 },{ prices: [2, 4, 1], expected: 2 },{ prices: [3], expected: 0 },];for (let { prices, expected } of testCases) {const result maxProfit(prices);console.assert(result expected, 测试失败输入 ${prices}期望输出 ${expected}实际输出 ${result});}console.log(所有测试用例通过);
}testMaxProfit();总结
核心思想在一次遍历中找到最低的买入价格和最高的卖出价格在买入之后。算法优势时间复杂度低只需要遍历一次数组空间复杂度为 O(1)。注意事项在更新 minPrice 时只更新更低的价格在计算利润时必须确保当前价格是在 minPrice 之后的。