LeeCode Practice Journal | Day28_GA02

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

题目:122. 买卖股票的最佳时机 II - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
拆成每一天,只要股票涨了,就算我们赚的

solution
public class Solution {
    public int MaxProfit(int[] prices) {
        int sum = 0;
        for(int i = 1; i < prices.Length; i++)
        {
            if(prices[i] > prices[i - 1]) sum += prices[i] - prices[i - 1];
        }
        return sum;
    }
}
summary

本来要算最高峰值和最低峰值的差值和,注意学会拆分

55. 跳跃游戏

题目:55. 跳跃游戏 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
思路比较清晰,不断更新覆盖范围

solution
public class Solution {
    public bool CanJump(int[] nums) {
        int cover = 0;
        for(int i = 0; i <= cover; i ++)
        {
            cover = cover > nums[i] + i ? cover : nums[i] + i;
            if(cover >= nums.Length - 1) return true;
        }
        return false;
    }
}
summary

错误:

能跳完的条件判定:cover >= nums.Length - 1

45. 跳跃游戏Ⅱ

题目:45. 跳跃游戏 II - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)

solution
public class Solution {
    public int Jump(int[] nums) {
        int result = 0;
        int cover = 0;
        int nextcover = 0;

        while(cover < nums.Length - 1)
        {
            for(int i = 0; i <= cover; i ++)
            {
                nextcover = nextcover > nums[i] + i ? nextcover : nums[i] + i;
            }
            result ++;
            cover = nextcover;
        }

        return result;
    }
}
summary

贪得是每一步尽可能走的远。。。

1005. K次取反后最大化的数组和

题目:1005. K 次取反后最大化的数组和 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
每次都选最小的数取反

solution
public class Solution {
    public int LargestSumAfterKNegations(int[] nums, int k) {
        int result = 0;
        Array.Sort(nums);
        for(int i = 1; i <= k; i ++)
        {
            if(nums[0] < 0)
            {
                nums[0] = -nums[0];
                Array.Sort(nums);
            }
            else if(nums[0] == 0)
            {
                break;
            }
            else
            {
                nums[0] = (k - i + 1) % 2 == 0 ? nums[0]:-nums[0];
                break;
            }
        }

        foreach(int j in nums)
        {
            result += j;            
        }
         return result;

    }
}
summary

可以直接重复排序+取反的过程
也可以加入条件判断优化

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值