代码随想录算法训练营Day32 | 贪心算法(2/6) Leetcode 122.买卖股票的最佳时机 II 55. 跳跃游戏 45.跳跃游戏II

开始贪心算法第二天的练习

第一题

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.

在价格最低的时候购买,相对高的时候售出,确保利益最大。这道题还是用局部最优来求出全局最优,是典型的贪心问题。

由于不能预测股票的走势,因此需要在股票相对高价的时候就卖出,过了那一天就不能卖出那个价格了,因此只能求出这个数列所有差值为正的情况,然后把他们加起来。

要注意剔除day0的时候,因为那一天的[i-1]会成为数组的倒数第一位,导致求出错误的结果

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            if prices[i]-prices[i-1] >= 0:
                profit += prices[i]-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.

这道题求的不是怎样跳步数最短,而只是问能不能跳出来,因此要看每一个跳跃的最大范围能不能覆盖完这个数组。

在跳的时候,cover负责计算跳跃的范围,如果cover大于这个数组,那说明一定可以跳出来。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        cover = 0
        if len(nums) == 1: return True
        i = 0
        while i <= cover:
            cover = max(i + nums[i], cover)
            if cover >= len(nums) - 1: return True
            i += 1
        return False

第三题

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].

从数组0的位置调到数组n-1的位置就算跳出来,但这道题要求返回最少跳跃次数。因为test cases已经可以保证能跳到n-1的位置,因此只需要设计次数最少的方法就行了。

class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return 0
        cur_distance = 0  
        ans = 0  
        next_distance = 0  
        for i in range(len(nums)):
            next_distance = max(nums[i] + i, next_distance) 
            if i == cur_distance:  
                ans += 1  
                cur_distance = next_distance  
                if next_distance >= len(nums) - 1: 
                    break
        
        return ans

你可能感兴趣的:(LeetCode,贪心算法,leetcode)