代码随想录算法训练营 day 32: ● 122.买卖股票的最佳时机II ● 55. 跳跃游戏 ● 45.跳跃游戏II

64 阅读1分钟

122. Best Time to Buy and Sell Stock II

这题从位置1开始扫,跟前一个比较。差值大于零的买卖,否则不动。

class Solution {
    public int maxProfit(int[] prices) {
        int diff = 0;
        int profit = 0;

        if(prices.length <= 1) {
            return 0;
        }

        for(int i=1; i<prices.length; i++) {
            diff = prices[i] - prices[i-1];

            if(diff > 0) {
                profit += diff;
            }
        }

        return profit;
        
    }
}

55. Jump Game 这题思路对了但写的很繁琐。因为只需要判断能不能走到最后一个元素,所以随时更新当前扫到位置的最远可达距离即可。如果扫到最远距离,还没到最后一个元素,就不能在扫了,因为走不到。

class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length <= 1) {
            return true;
        }

        int maxReach = 0;

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

        return false;
    }
}

45. Jump Game II 这题有思路但写不出来。算法描述是:

  1. 从头扫数组,在每一个位置更新最大可达距离,作为下一步最远能走到哪里的指示
  2. 另外要有一个当前步数最大距离,记录当前这一步最远能到哪。
  3. 还要有一个步数记录,i即可充当。
  4. 在步数到达当前步数最大距离时,step++, 当前最大距离更新为下一步最大距离。
  5. 要注意每一次循环,下一步最大距离都有可能更新,但只要当前步数最大还没到,就意味着下一步总是可以走到下一步最大距离的。
class Solution {
    public int jump(int[] nums) {
        if(nums.length == 1) {
            return 0;
        }

        int curReach = 0;
        int count = 0;
        int nextReach = 0;

        for(int i=0; i<= nums.length - 1; i++) {
            nextReach = Math.max(nums[i] + i, nextReach);

            if(i == curReach) {
                count++;
                curReach = nextReach;
                if(nextReach >= nums.length - 1) {
                    break;
                }

            }


        }

        return count;
    }
}