第八章 贪心算法 part02

67 阅读1分钟

122. Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

题目解析:

  • 贪心思想,如果后一个比当前值小,则从后一个开始重新买入;如果后一个比当前值大,则买入当前值,再下一个再卖出

代码:

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

55. Jump Game

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

题目解析:

  • 判断之前的能否跳到当前位置,直到最后一个, 如果中间有位置不可达,返回false

代码:

class Solution {
    public boolean canJump(int[] nums) {
        int reached = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > reached) return false;
            reached = i + nums[i] > reached ? i + nums[i]: reached;
        }
        return true;
    }
}

45. Jump Game II

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

  • 0 <= j <= nums[i] and
  • i + j < n

Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

题目解析:

  • 走到前一步所能到的最大距离时再步数+1

代码:

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