作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn8fsh/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    这里只允许买入/抛出一次
    给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
    你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
    返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

    1. 示例 1
    2. 输入:[7,1,5,3,6,4]
    3. 输出:5
    4. 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5
    5. 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
    6. 示例 2
    7. 输入:prices = [7,6,4,3,1]
    8. 输出:0
    9. 解释:在这种情况下, 没有交易完成, 所以最大利润为 0

    思路一:
    定义最小值和最大利润两个变量,遍历比较最小值及最大利润即可

    1. /**
    2. * @param {number[]} prices
    3. * @return {number}
    4. */
    5. var maxProfit = function(prices) {
    6. let minPrice = prices[0];
    7. let maxProfit = 0;
    8. for(let i = 0; i < prices.length; i++) {
    9. if (prices[i] < minPrice) {
    10. minPrice = prices[i];
    11. }
    12. let curProfit = prices[i] - minPrice;
    13. if (curProfit > maxProfit) {
    14. maxProfit = curProfit;
    15. }
    16. }
    17. return maxProfit
    18. };

    参考:
    动态规划,区别于题目 股票II,这里只允许买入/抛出一次,状态还是天数和是否买入,但是第i 天买入的最大利润dp[i][1] 的转移方程就不太一样了:

    之前任何一天都没有买入,今天买入的最大利润就是-prices[i],而非dp[i-1][0] - prices[i];
    之前某一天买入,今天继续持有的最大利润就是dp[i - 1][1];

    1. function maxProfit(prices: number[]): number {
    2. const dp = [[0, -prices[0]]];
    3. for (let i = 1; i < prices.length; i++) {
    4. dp[i] = new Array(2);
    5. dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
    6. dp[i][1] = Math.max(- prices[i], dp[i - 1][1]);
    7. }
    8. return dp[prices.length - 1][0];
    9. };

    https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/you-qian-ru-shen-san-chong-jie-fa-jian-ji-yi-dong-/