买卖股票的最佳时机 II【贪心策略】

  1. 买卖股票的最佳时机 II
    给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。
在这里插入图片描述

class Solution {
    
    //思路:只关注最后的利润而无需关心何时买入和卖出。
    public int maxProfit(int[] prices) {
    
    
        int sum = 0;

        for (int i = 0; i < prices.length - 1; i++) {
    
    
            int dif = prices[i + 1] - prices[i];
            //计算每日利润;只要为正,就加入结果中(局部最优),并收集所有正的利润,即为全局最优。
            //贪心策略,只收集正的利润,并将它们累加作为最终的结果返回
            if (dif > 0) {
    
    
                sum += dif;
            }
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47004707/article/details/132515662