【LeetCode每日一题合集】2023.10.2-2023.10.8(股票系列 & ⭐数据结构)

122. 买卖股票的最佳时机 II(DP | 贪心)

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/?envType=daily-question&envId=2023-10-02
在这里插入图片描述

解法1——动态规划

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[] buy = new int[n], sell = new int[n];
        buy[0] = -prices[0];
        for (int i = 1; i < n; ++i) {
            buy[i] = Math.max(sell[i - 1] - prices[i], buy[i - 1]);
            sell[i] = Math.max(buy[i - 1] + prices[i], sell[i - 1]);
        }
        return sell[n - 1];
    }
}

解法2——贪心

贪心:能赚钱就赚。

class Solution {
    public int maxProfit(int[] prices) {
        int ans = 0;
        for (int i = 1; i < prices.length; ++i) {
            ans += Math.max(0, prices[i] - prices[i - 1]);
        }
        return ans;
    }
}

123. 买卖股票的最佳时机 III(动态规划)

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/description/?envType=daily-question&envId=2023-10-03

在这里插入图片描述

提示:
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^5

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[] buy = new int[2], sell = new int[2];
        Arrays.fill(buy, -prices[0]);
        for (int i = 0; i < n; ++i) {
            buy[0] = Math.max(buy[0], -prices[i]);
            sell[0] = Math.max(sell[0], buy[0] + prices[i]);
            buy[1] = Math.max(buy[1], sell[0] - prices[i]);
            sell[1] = Math.max(sell[1], buy[1] + prices[i]);
        }
        return sell[1];
    }
}

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

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/?envType=daily-question&envId=2023-10-04

在这里插入图片描述

提示:
1 <= k <= 100
1 <= prices.length <= 1000
0 <= prices[i] <= 1000

class Solution {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        int[][] buy = new int[n][k], sell = new int[n][k];
        for (int j = 0; j < k; ++j) buy[0][j] = -prices[0];
        for (int i = 1; i < n; ++i) {
            buy[i][0] = Math.max(-prices[i], buy[i - 1][0]);
            sell[i][0] = Math.max(buy[i - 1][0] + prices[i], sell[i - 1][0]);
            for (int j = 1; j < k; ++j) {
                buy[i][j] = Math.max(sell[i - 1][j - 1] - prices[i], buy[i - 1][j]);
                sell[i][j] = Math.max(buy[i - 1][j] + prices[i], sell[i - 1][j]);
            }
        }
        return sell[n - 1][k - 1];
    }
}

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

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/?envType=daily-question&envId=2023-10-05

在这里插入图片描述

让 buy[i] 从 sell[i-2] 转移过来就好了。

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if (n == 1) return 0;
        int[] buy = new int[n], sell = new int[n];
        buy[0] = -prices[0];
        buy[1] = Math.max(buy[0], -prices[1]);
        sell[1] = Math.max(0, prices[1] - prices[0]);
        for (int i = 2; i < n; ++i) {
            buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]);
            sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
        }
        return sell[n - 1];
    }
}

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

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/?envType=daily-question&envId=2023-10-06
在这里插入图片描述

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int[] buy = new int[n], sell = new int[n];
        buy[0] = -prices[0];
        for (int i = 1; i < n; ++i) {
            buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i]);
            sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i] - fee);
        }
        return sell[n - 1];
    }
}

901. 股票价格跨度(单调栈)

https://leetcode.cn/problems/online-stock-span/description/?envType=daily-question&envId=2023-10-07
在这里插入图片描述
提示:
1 <= price <= 10^5
最多调用 next 方法 10^4 次

单调栈中的每个元素是{日期,当日价格}。

class StockSpanner {
    Deque<int[]> stk = new LinkedList<>();
    int idx = 1;

    public StockSpanner() {
        stk.push(new int[]{0, 100001});
    }
    
    public int next(int price) {
        while(stk.size() > 1 && price >= stk.peek()[1]) {
            stk.pop();
        }
        int res = idx - stk.peek()[0];
        stk.push(new int[]{idx, price});
        idx++;
        return res;
    }
}

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 */

2034. 股票价格波动⭐(数据结构)

https://leetcode.cn/problems/stock-price-fluctuation/description/?envType=daily-question&envId=2023-10-08

在这里插入图片描述
提示:

1 <= timestamp, price <= 10^9
update,current,maximum 和 minimum 总 调用次数不超过 10^5 。
current,maximum 和 minimum 被调用时,update 操作 至少 已经被调用过 一次 。

解法1——哈希表+两个优先队列

哈希表存储每个时间戳对应的价格。
两个优先队列分别按价格升序和降序排列。当取出队首的价格和哈希表中存储的冲突时,不采用,而是继续取下一个元素直到不冲突为止。

class StockPrice {
    int lastTimeStamp = 0;
    Map<Integer, Integer> timePriceMap;
    PriorityQueue<int[]> pqMax, pqMin;

    public StockPrice() {
        timePriceMap = new HashMap<Integer, Integer>();
        pqMax = new PriorityQueue<int[]>((a, b) -> b[0] - a[0]);    // 倒序
        pqMin = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);    // 升序
    }
    
    public void update(int timestamp, int price) {
        lastTimeStamp = Math.max(lastTimeStamp, timestamp);
        timePriceMap.put(timestamp, price);
        pqMax.offer(new int[]{price, timestamp});
        pqMin.offer(new int[]{price, timestamp});
    }
    
    public int current() {
        return timePriceMap.get(lastTimeStamp);
    }
    
    public int maximum() {
        while (true) {
            int[] priceTime = pqMax.peek();
            int price = priceTime[0], timestamp = priceTime[1];
            if (timePriceMap.get(timestamp) == price) return price;
            pqMax.poll();
        }
    }   
    
    public int minimum() {
        while (true) {
            int[] priceTime = pqMin.peek();
            int price = priceTime[0], timestamp = priceTime[1];
            if (timePriceMap.get(timestamp) == price) return price;
            pqMin.poll();
        }
    }
}

/**
 * Your StockPrice object will be instantiated and called as such:
 * StockPrice obj = new StockPrice();
 * obj.update(timestamp,price);
 * int param_2 = obj.current();
 * int param_3 = obj.maximum();
 * int param_4 = obj.minimum();
 */

解法2——哈希表+有序集合

哈希表存储每个时间戳对应的价格。
有序集合存储目前已经出现过的价格及其对应的出现次数。

在更新每个时间戳的价格之前,先使用其之前的价格更新有序集合即可。

class StockPrice {
    int lastTimeStamp = 0;
    Map<Integer, Integer> timePriceMap;
    TreeMap<Integer, Integer> prices;

    public StockPrice() {
        timePriceMap = new HashMap<Integer, Integer>();
        prices = new TreeMap<>();
    }
    
    public void update(int timestamp, int price) {
        lastTimeStamp = Math.max(lastTimeStamp, timestamp);
        int prevPrice = timePriceMap.getOrDefault(timestamp, 0);
        timePriceMap.put(timestamp, price);
        if (prevPrice > 0) {    // 如果出现过
            prices.merge(prevPrice, -1, Integer::sum);
            if (prices.get(prevPrice) == 0) prices.remove(prevPrice);
        }
        prices.merge(price, 1, Integer::sum);
    }
    
    public int current() {
        return timePriceMap.get(lastTimeStamp);
    }
    
    public int maximum() {
        return prices.lastKey();
    }   
    
    public int minimum() {
        return prices.firstKey();
    }
}

/**
 * Your StockPrice object will be instantiated and called as such:
 * StockPrice obj = new StockPrice();
 * obj.update(timestamp,price);
 * int param_2 = obj.current();
 * int param_3 = obj.maximum();
 * int param_4 = obj.minimum();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wei *

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

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

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

打赏作者

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

抵扣说明:

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

余额充值