boxmoe_header_banner_img

Hello! 欢迎来到不如画七的空间!

加载中

文章导读

05.买卖股票的最佳时机Ⅱ


avatar
ensiezadi 2025年8月27日 35

买卖股票的最佳时机Ⅱ

题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

具体思路

统计相邻的两天之间买卖的正负关系

如果是坡峰那一定可以通过每段得到最大, 同时也可以去掉坡谷

具体代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for (int i = 0; i < prices.size() - 1; i++) {
            prices[i] = prices[i + 1] - prices[i];
            if (prices[i] > 0)
                res += prices[i];
        }
        return res;
    }
};
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); i++) {
            res += max(prices[i] - prices[i - 1], 0);
        }
        return res;
    }
};

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


评论(0)

查看评论列表

暂无评论


发表评论

表情 颜文字
插入代码
不如画七
2025 年 10 月
 123456
78910111213
14151617181920
21222324252627
282930