We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
解题思路:
对于第i天,我们需要知道两种状态:
i
0
cost
cost = Math.min(cost, prices[i]);
profit
profit = prices[i] - cost
i - 1
profit = Math.max(prices[i] - cost, profit);
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let cost = prices[0]; // 从第一天到第i天买入股票的最小花费 let profit = 0; // 从第一天到第i天卖出股票的最大利润 // 从1开始遍历prices进行递推 for (let i = 1; i < prices.length; i++) { // 到i为止已知的最小价格,是i之前已知的最小价格,与当前价格之间的较小者 cost = Math.min(cost, prices[i]); // 到i为止产生的最大利润,是i之前产生的最大利润,与当前卖出的最大利润中的较大者 profit = Math.max(prices[i] - cost, profit); } // 递推到最后就得到了最大利润 return profit; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
解题思路:
对于第
i
天,我们需要知道两种状态:0
到i
天,股票最低价格,用cost
表示,即为cost = Math.min(cost, prices[i]);
i
天卖出股票能获得的利润,用profit
表示,即为profit = prices[i] - cost
。我们可以将其与0
到i - 1
天的最大利润对比,那么遍历完成时profit
就是最大利润,即为profit = Math.max(prices[i] - cost, profit);
The text was updated successfully, but these errors were encountered: