买卖股票的最佳时机I、II、III、IV

本文介绍了一种用于确定最佳股票买卖时机的算法。该算法通过一次遍历找出最大利润,并提供了适用于不同交易次数限制的解决方案,包括一次交易、多次交易及固定次数交易的最佳策略。

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

买卖股票的最佳时机I

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
思路:这个比较简单,只要遍历一次就好,同时更新最小的值。可以得到最大的利润。
代码如下:

class Solution {
public:
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        if(prices.size()<2)return 0;//防止越界
        int maxprofit = 0;//最大利润
        int minlow = prices[0];//最低价格
        for(int i = 1;i != prices.size();++i){
            minlow = min(minlow,prices[i]);
            maxprofit = max(maxprofit,prices[i] - minlow);
        }
        return maxprofit;
    }
};

买卖股票的最佳时机II

假设有一个数组,它的第i个元素是一个给定的股票在第i天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。
思路:这个问题,显然只要能有收益的时候就脱出卖,这样就可以获得最大的利润。
代码如下:

class Solution {
public:
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        //这里应该是有利润就要出手
        if(prices.size()<2)return 0;
        int low = prices[0];
        int profit = 0;
        for(int i=1;i!=prices.size();++i){
            if(prices[i]>low){
                profit = profit+prices[i]-low;
            }
            low = prices[i];
        }
        return profit;
    }
};

买卖股票的最佳时机III&IV

假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成 k 笔交易。注意事项:你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
样例
给定价格 = [4,4,6,1,1,4,2,5], 且 k = 2, 返回 6.
思路:典型的动态规划问题。
代码如下:

public class Solution {
    /*
     * @param K: An integer
     * @param prices: An integer array
     * @return: Maximum profit
     */
    public int maxProfit(int K, int[] prices) {
        int len = prices.length;
        if (K >= len / 2) return quickSolve(prices);

        int[][] t = new int[K + 1][len];
        for (int i = 1; i <= K; i++) {
            int tmpMax =  -prices[0];
            for (int j = 1; j < len; j++) {
                t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax);
                tmpMax =  Math.max(tmpMax, t[i - 1][j - 1] - prices[j]);
            }
        }
        return t[K][len - 1];
    }
   private int quickSolve(int[] prices) {
        int len = prices.length, profit = 0;
        for (int i = 1; i < len; i++)
        // as long as there is a price gap, we gain a profit.
        if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
        return profit;
   }
}

另一种简单的解法

在Discuss中看到一种很棒的解法,代码只有10行左右,但是不是很好理解。

第二种解法的核心是假设手上最开始只有0元钱,那么如果买入股票的价格为price,手上的钱需要减去这个price,如果卖出股票的价格为price,手上的钱需要加上这个price。

它定义了4个状态:

Buy1[i]表示前i天做第一笔交易买入股票后剩下的最多的钱;

Sell1[i]表示前i天做第一笔交易卖出股票后剩下的最多的钱;

Buy2[i]表示前i天做第二笔交易买入股票后剩下的最多的钱;

Sell2[i]表示前i天做第二笔交易卖出股票后剩下的最多的钱;

那么

Sell2[i]=max{Sell2[i-1],Buy2[i-1]+prices[i]}
Buy2[i]=max{Buy2[i-1],Sell[i-1]-prices[i]}
Sell1[i]=max{Sell[i-1],Buy1[i-1]+prices[i]}
Buy1[i]=max{Buy[i-1],-prices[i]}

可以发现上面四个状态都是只与前一个状态有关,所以可以不使用数组而是使用变量来存储即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy1=numeric_limits<int>::min();
        int buy2=numeric_limits<int>::min();
        int sell1=0;
        int sell2=0;
        for(int i=0;i<prices.size();i++)
        {
            sell2=max(sell2,buy2+prices[i]);
            buy2=max(buy2,sell1-prices[i]);
            sell1=max(sell1,buy1+prices[i]);
            buy1=max(buy1,-prices[i]);
        }
        return sell2;
    }

};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值