leetcode难题之Best time to buy and sell stock大合集

本文详细探讨了LeetCode中的一系列股票问题,包括一次交易、多次交易、最多买卖两次、最多买卖k次、带有冷却期和手续费的情况。通过动态规划策略,逐一解析每种情况下的最佳买卖时机,旨在帮助读者掌握此类问题的通用解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次带来的是Best time to buy and sell stock大合集,在leetcode上这一合集共有6道题,难度从easy到hard不等,我们这次记录下这一合集的全部解法并记录下解题的思考想法。所有的题目都是计算不同计算规则下股票的最大利润。

一,Best Time to Buy and Sell Stock (一次交易)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

本题意思就是你得到一系列在接下来几天的股票价格,现在你被允许只用一次交易(就是买进再卖出)来获取最大利益。 这个很简单,只要用双指针的方法记住获利的大小,再筛选出最大的即可。

我的解法:

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

二,Best Time to Buy and Sell Stock Ⅱ(多次交易)

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

意思是买卖股票时可以不计买卖次数,但是必须在买之前先把以前的股票卖掉。然后求能获利最大的额度。 这样的话也很简单,只要遇见下一天的价格比这一天价格高的话,就卖出,这样最后的利润肯定是最高的。(市场放开,有利就图啊)

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

三,Best Time to Buy and Sell Stock III(最多买卖两次)

Say you have an array for which the ith element is the price of a given stock on day i.

Desig

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值