代码随想录训练营第三十一天 | 贪心算法

贪心算法的核心思想是在每一步决策中都找到局部最优解

122. 买卖股票的最佳时机

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

去看今天的股票价格是否大于昨天的就可以了,如果大于的话,那返回值就加上他们的差价。

55. 跳跃游戏

class Solution {
    public boolean canJump(int[] nums) {

        int n = nums.length;
        if(n == 1){
            return true;
        }
        int longest = 0;
        for(int i = 0; i<= longest; i++){
            longest = Math.max(longest, i + nums[i]);
            if(longest >= n-1){
                return true;
            }
        }
        return false;
    }
}

每次取数组中已经经过的最大值,去看他们最远是否可以覆盖到数组长度-1, 如果覆盖面全都无法达到,那么就返回false;

45. 跳跃游戏2

class Solution {
    public int jump(int[] nums) {
        int n = nums.length;
        int res = 0;
        int end = 0;
        int temp = 0;
        for(int i = 0; i<=end ; i++){
            if(end >= n-1){
                return res;
            }
            temp = Math.max(temp, i + nums[i]);

            if(i == end){
                end = temp;
                res++;
            }

        }
        return res;
    }
}

和上一题思路基本相似,只不过要在不断扩大覆盖面积后加上1,用来计算重新覆盖的次数

 

今天是贪心算法,第一天感觉良好

posted @ 2022-11-12 15:27  小猫Soda  阅读(26)  评论(0)    收藏  举报