首页 > 试题广场 >

买卖股票的最好时机(二)

[编程题]买卖股票的最好时机(二)
  • 热度指数:46046 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
假设你有一个数组prices,长度为n,其中prices[i]是某只股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1. 你可以多次买卖该只股票,但是再次购买前必须卖出之前的股票
2. 如果不能获取收益,请返回0
3. 假设买入卖出均无手续费

数据范围:
要求:空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度
示例1

输入

[8,9,2,5,4,7,1]

输出

7

说明

在第1天(股票价格=8)买入,第2天(股票价格=9)卖出,获利9-8=1
在第3天(股票价格=2)买入,第4天(股票价格=5)卖出,获利5-2=3
在第5天(股票价格=4)买入,第6天(股票价格=7)卖出,获利7-4=3
总获利1+3+3=7,返回7        
示例2

输入

[5,4,3,2,1]

输出

0

说明

由于每天股票都在跌,因此不进行任何交易最优。最大收益为0。            
示例3

输入

[1,2,3,4,5]

输出

4

说明

第一天买进,最后一天卖出最优。中间的当天买进当天卖出不影响最终结果。最大收益为4。                

备注:
总天数不大于200000。保证股票每一天的价格在[1,100]范围内。
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型vector 股票每一天的价格
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        int res=0;
        for(int i=1;i<prices.size();i++) {
            if(prices[i]>prices[i-1]) {
                res+=prices[i]-prices[i-1];
            }
        }
        return res;
    }
};

发表于 2021-03-20 21:51:33 回复(0)
只要涨价,我就先买后卖,将差价加入结果中。
只要降价,就按兵不动,更新当前位置。
function maxProfit( prices ) {
    let curr=prices[0]
    let res=0
    for(let i=1;i<prices.length;i++){
        if(prices[i]>curr){
            res+=prices[i]-curr
            curr=prices[i]
        }else{
            curr=prices[i]
        }
    }
    return res
}


发表于 2021-03-14 23:03:33 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        //持有股票1和不持有股票0两种状态,第0天和第1,2,3...第prices.length天
        int[][] dp = new int[2][prices.length + 1];

        //第0天未持有股票,收益为0
        dp[0][0] = 0;
        //第0天持有股票,不存在,收益为负无穷
        dp[1][0] = Integer.MIN_VALUE;

        for (int i = 1; i <= prices.length; i++) {
            //第i天未持有股票,两个可能:
            //1.在前面i-1天都持有,第i天卖掉了,卖掉价值增加。dp[1][i - 1] + prices[i - 1]
            //2.到当前为止都为未持有,维持第i-1天的结果。dp[0][i - 1]
            dp[0][i] = Math.max(dp[0][i - 1], dp[1][i - 1] + prices[i - 1]);
            //第i天持有股票,两个可能:
            //1.在前面i-1天都未持有,第i天买入了,总价值减少。dp[0][i - 1] - prices[i - 1]
            //2.到当前为止都为持有,维持第i-1天的结果。dp[1][i - 1]
            dp[1][i] = Math.max(dp[1][i - 1], dp[0][i - 1] - prices[i - 1]);
        }

        //获取最后一天卖掉的最大值
        return dp[0][prices.length];
    }
}

编辑于 2021-04-19 15:31:09 回复(0)
投机取巧的方法 只要涨我就卖,当天我可以卖了再买 跟真实的股市不一样
public class Solution {
    public int maxProfit (int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i-1])
                profit += prices[i] - prices[i-1];
        }
        return profit;
    }
}
发表于 2021-08-06 11:59:00 回复(2)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int profit=0;
        for(int i=1;i<prices.length;i++){
           if(prices[i]>prices[i-1]){
             profit+=prices[i]-prices[i-1];  
           }
        }
        return profit;
    }
}

发表于 2021-01-21 17:57:38 回复(0)
int maxProfit(vector<int>& prices) {
        //完成无限次的交易
        int size=prices.size();
        vector<vector<int>> dp(size,vector<int>(2,0));//1=持有 0=未持有
        dp[0][0]=0;
        dp[0][1]=-prices[0];
        for(int i=1;i<size;++i){
            dp[i][0]=std::max(dp[i-1][0],dp[i-1][1]+prices[i]);
            dp[i][1]=std::max(dp[i-1][1],dp[i-1][0]-prices[i]);
        }
        return dp[size-1][0];
    }

发表于 2020-09-19 22:26:50 回复(0)
int maxProfit(int* prices, int n ) {
    int sum = 0;
    int i = 0;
    if(n < 2) return 0;
    while(i < n-1) {    //将股票价格画成折线图,计算上升沿的总长度
        if(prices[i] < prices[i+1]) {
            sum += prices[i+1] - prices[i];
        }
        i++;
    }
    return sum;
}
发表于 2023-01-08 23:25:54 回复(0)
股市有风险,投资需谨慎
发表于 2021-11-20 16:49:14 回复(0)
    public int maxProfit (int[] prices) {
        int n=prices.length,profit=0;
        for(int i=1;i<n;i++){
            if(prices[i]>prices[i-1])
                profit+=prices[i]-prices[i-1];
        }
        return profit;
    }

发表于 2021-02-05 16:22:29 回复(1)
function maxProfit( prices ) {
    // write code here
    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
}

发表于 2023-12-01 10:38:38 回复(0)
我怎么觉得这一题比第一部分还要简单
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        if len(prices)>= 1:
            a = [0]*len(prices)
            for i in range(1,len(prices)):
                a[i] = max(prices[i]-prices[i-1],0)
            return sum(a)
        else:
            return 0


发表于 2023-03-17 00:26:09 回复(0)
需要毛的动态规划啊。直接遍历求解
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # write code here
        n = len(prices)
        if n < 2:
            return 0
        
        res = 0
        i = 0
        while i < n-1:
            if prices[i+1] > prices[i]:
                res += prices[i+1] - prices[i]
                i += 1
            else:
                i += 1
        return res

发表于 2022-12-04 16:54:58 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型vector 股票每一天的价格
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // 时间复杂度O(N),空间复杂度O(N)
        if (prices.empty()) return 0;
        int dp[2][prices.size()];
        dp[0][0] = -prices[0], dp[1][0] = 0;
        for (int i = 1; i < prices.size(); ++i) {
            dp[0][i] = max(dp[0][i - 1], dp[1][i - 1] - prices[i]);
            dp[1][i] = max(dp[1][i - 1], dp[0][i - 1] + prices[i]);
        }
        return dp[1][prices.size() - 1];
    }
};

发表于 2022-11-09 11:19:37 回复(0)
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        n = len(prices)
        #dp[i][0]表示某一天不持股到该天为止的最大收益,dp[i][1]表示某天持股,到该天为止的最大收益
        dp = [[0] * 2 for i in range(n)]
        #第一天不持股,总收益为0
        dp[0][0] = 0
        #第一天持股,总收益为减去该天的股价
        dp[0][1] = -prices[0]
        #遍历后续每天,状态转移
        for i in range(1, n):
            # 第i天不持股有两种情况,第一种昨天就没有买股票,第二种昨天卖出了股票(这里一直保存最大收益,整个过程下来相当于只买了一次)
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
            # 第i天持股有两种情况,第一种昨天就持股,第二种昨天不持股,但是今天买入了(这里相当于寻找最最小值了)
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i])
        #最后一天不持股,到该天为止的最大收益
        return dp[n - 1][0]

发表于 2022-08-04 16:12:42 回复(2)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int profits = 0;
        int len = prices.length;
        for(int i =1;i<len;i++){
            if(prices[i]>prices[i-1]){
                profits+=prices[i]-prices[i-1]; //逢高卖出
            }
        }
        return profits;
    }
}

发表于 2021-07-15 23:10:22 回复(0)
class Solution:
    def maxProfit(self , prices ):
        # write code here
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                profit += prices[i]-prices[i-1]
        return profit


发表于 2021-03-12 20:59:19 回复(0)
public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            res += Math.max(prices[i] - prices[i - 1], 0);
        }
        return res;
    }
}

发表于 2026-02-17 19:54:51 回复(0)
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 计算最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
 */
export function maxProfit(prices: number[]): number {
    // write code here
    const { length } = prices
    const dp = (new Array(length)).fill(
        // 二元元组:[当天持有股票的收益, 当天未持有股票的收益]
        (new Array(2)).fill(0)
    )

    for (let i = 0; i < length; i++) {
        // 当天持有股票
        if (!i) {
            dp[i][0] = -prices[i]
        } else {
            dp[i][0] = Math.max(
                // 已有,保留,依然是上一天持有股票时的利润
                dp[i - 1][0],
                // 没有,买入,上一天的利润 减去当天的价格
                dp[i - 1][1] - prices[i]
            )
            // 当天未持有股票
            dp[i][1] = Math.max(
                // 没有,不买
                dp[i - 1][1],
                // 已有,卖出
                dp[i - 1][0] + prices[i]
            )
        }
    }

    return dp[length - 1][1]
}


发表于 2026-01-18 22:19:20 回复(0)
class Solution:
    def maxProfit(self , prices: list[int]):
        max_value = 0
        for i in range(len(prices)-1):
            value = prices[i+1] - prices[i]
            if value > 0:
                max_value += value
        return max_value
发表于 2025-10-26 12:27:53 回复(0)
class Solution
{
public:
    /*
        这类题型就是多状态dp的类型。通常需要多个数组或者多维数组表示。

        对于买卖股票,无论何时,只存在两种状态。
        每一天有两种状态,这天买入或者卖出。
        我们这样规定,在0 ~ i天内,当前处于买入状态或者卖出状态。我们以f[i],g[i]分别
    表示前i天(包括i)处于买入状态或者卖出状态时的最大金额/利润。
            (1).若当前处于买入状态,要区分具体是那一天买入的:
                1.若是第i天买入,那么说明前i - 1要么卖出过,然后买入;要么前i -1天内从来没买入,在第i天买入;
            而我们知道,前i - 1天卖出过的状态必然要优于前面i - 1天从来没有买入过的状态,因为
            卖出状态下我们认为必然是有利润的。
                    也就是说,此时状态可以归纳为:当第i天买入,前i-1天某天卖出过,此时状态
                转移方程为:f[i] = g[i - 1] + (-prices[i]);
                2.若是第i天没有买入,那么说明前i - 1天内必然买入过,此时:f[i] = f[i - 1];

            买入状态下,获取两者最大值:f[i] = max(g[i - 1] - prices[i], f[i - 1]);

            (2).若处于卖出状态,要区分哪一天卖出的。
                1.若第i天卖出,那么前面可能前面i -1 天某天买入了,或者今天买入了;而今天买入属于无效状态,因此,此时:g[i] = f[i - 1] + prices[i];
                2.若第i天不卖出,那么此时可能前面i - 1天内某天卖出了,或者从来没有卖出过,很明显前面i - 1天内卖出更优,因此,此时:g[i] = g[i - 1];

            卖出状态下,获取两者最大值:g[i] = max(f[i - 1] + prices[i], g[i - 1]);
   
        目标值为g[n - 1],即最后买入必然比最后一天卖出更优。
    */

    int maxProfit(vector<int>& prices)
    {
        int n = prices.size();

        vector<int> f(n), g(n);
        f[0] = -prices[0];
        for(int i = 1; i < n; i++)
        {
            f[i] = max(g[i - 1] - prices[i], f[i - 1]);
            g[i] = max(g[i - 1], prices[i] + f[i - 1]);
        }

        return g[n - 1];
    }
};
发表于 2025-09-26 22:39:26 回复(0)

问题信息

难度:
103条回答 11500浏览

热门推荐

通过挑战的用户

查看代码
买卖股票的最好时机(二)