0
点赞
收藏
分享

微信扫一扫

每日一题-贪心算法

m逆光生长 2024-04-29 阅读 43

目录

前言

买入股票的最佳时机(1)

买入股票的最好时机(2)

前言

买入股票的最佳时机(1)

. - 力扣(LeetCode)

 

代码实现,我把上面的思路分析都用代码注释标注了

class Solution {
    public int maxProfit(int[] arr) {
        int min = Integer.MAX_VALUE;// 记录i - 1位置的最小值
        int max = Integer.MIN_VALUE;// 卖出股票会得到的最大利润

        for (int i = 0; i < arr.length - 1; i++) {
            min = Math.min(min, arr[i]);// 计算前面的最小值
            max = Math.max(max, arr[i + 1] - min);// 更新最大值
        }
        return Math.max(max, 0);
    }
}

买入股票的最好时机(2)

. - 力扣(LeetCode)

class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        for(int i = 1;i < prices.length;i++){//从第二个位置开始
            if(prices[i] > prices[i - 1]){
//通过求每一段增长区间的值来求最终增长区间的值(每个增长区间我都要)
                result += prices[i] - prices[i - 1];
            }
        }
        return result;
    }
}

因为买入股票最好时机3和4都是动态规划实现的,我将在下一篇进行讲解 

总结

举报

相关推荐

0 条评论