LeetCode3道股票题

本文探讨了LeetCode中三道股票交易问题:121. Best Time to Buy and Sell Stock,122. Best Time to Buy and Sell Stock II,123. Best Time to Buy and Sell Stock III。针对每道题目,分别给出了动态规划和数组应用的解决方案,旨在找到每次交易的最大利润。
摘要由CSDN通过智能技术生成

121. Best Time to Buy and Sell Stock

题目:买操作必须在卖操作之前,最多交易一次。得到最大利润
关键词: 动态规划, array
思路

  1. 动态规划初始值和动态变量(不需要数组,因为只需要最大profit值,和求子数组最大max一样)。
  2. 因为只是交易一次,只要确定谁是卖价和买价。初始买价格,判断prices[i] - buy 是否比存的profit大。如果是,更新profit。判断prices[i]和buy谁大,如果新的prices[i]比存的buy小,更新buy。

解答

var maxProfit = function(prices) {
    if (!prices || prices.length < 2) return 0; //no profit
    let profit = 0; //dp result
    let buy = prices[0];
    for (let i = 1; i < prices.length; i++){
        profit = Math.max(profit, prices[i] - buy);
        if (prices[i] < buy) buy = prices[i];
    }
    return profit;
};

122. Best Time to Buy and Sell Stock II

题目:买操作必须在卖操作之前,尽可能多次交易。得到最大利润
关键词: 动态规划, array
思路

  1. 谷地就是买入价,峰就是买出价。
  2. 每次判断当前和前面一个相比,如果当前大,则累加差值到profit;

解答

var maxProfit = function(prices) {
    if (!prices || prices.length < 2) return 0; //no profit
    let profit = 0;
    for (let i = 1; i< prices.length; i++){
        if (prices[i] > prices[i-1]){
            profit += (prices[i] - prices[i-1]);
        }
    }
    return profit;
};

123.Best Time to Buy and Sell Stock III

题目: 最多两次交易
关键词:动态规划,分治法
思路

  1. 最多两次交易->找到两个子数组,让其两个数组交易利益的总和最大。
  2. 考虑如何分割。第一部分从左到右,先确定low买入价,遍历当前价格(卖出价),找到当前i时候利益最大,同时有必要需要更新更低买入价。
  3. 第二部分,先确定high卖出价,遍历当前价格(买入价),找到当前i利益最大,同时有必要需要更新更高的卖出价。
  4. 最后,结合两个子数组,找到相加的最大值,就是最佳切割点。

解答

var maxProfit = function(prices) {
    if (!prices || prices.length < 2) return 0;
    let part1 = new Array(prices.length).fill(0);
    let part2 = new Array(prices.length).fill(0);
    let buy = prices[0];
    let high = prices[prices.length-1];
    for (let i = 1; i < prices.length; i++){
        part1[i] = Math.max(prices[i] - buy, part1[i-1]);//value ascend
        if (prices[i] < buy) buy = prices[i];
    }
    for (let i = prices.length - 2; i >= 0; i--){
        part2[i] = Math.max(high - prices[i], part2[i+1]);
        if (prices[i] > high) high = prices[i];
    }
    let profit = 0;
    for (let i =0; i < prices.length; i++){
        profit = Math.max(profit, part1[i] + part2[i]);
    }
    return profit;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值