【力扣】 - “买卖股票”问题

1. 买卖股票的最佳时机

(以下均忽略暴力求解)

一次遍历

策略:

既然只有一次交易,那么可以通过遍历来寻找最大的差值

过程:

使用数组逐个存储元素
寻找后面元素的最低值
更新并存储其差值

时间复杂度:O(n)
空间复杂度:O(1)

public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }
}

2. 买卖股票的最佳时机 II

贪心算法

策略:

  • 隔日上涨:今天买入,明天卖出
  • 多日上涨:持有股票到最高点再卖出
  • 隔日 / 多日下跌:不交易
遍历数组
若数值递增则直至下跌的前一天卖出
若数值递减则不交易
统计利润总值

时间复杂度:O(n)
空间复杂度:O(1)

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            int tmp = prices[i] - prices[i - 1];
            if (tmp > 0) profit += tmp;
        }
        return profit;
    }
}

3. 买卖股票的最佳时机 III

时间复杂度:O(n)
空间复杂度:O(1)

var maxProfit = function(prices) {
    const n = prices.length;
    let buy1 = -prices[0], buy2 = -prices[0];
    let sell1 = 0, sell2 = 0;
    for (let i = 1; i < n; i++) {
        buy1 = Math.max(buy1, -prices[i]);
        sell1 = Math.max(sell1, buy1 + prices[i]);
        buy2 = Math.max(buy2, sell1 - prices[i]);
        sell2 = Math.max(sell2, buy2 + prices[i]);
    }
    return sell2;
};

4. 买卖股票的最佳时机 IV

5. 最佳买卖股票时机含冷冻期

6. 买卖股票的最佳时机含手续费

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘泽宇Developer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值