【leetcode】1340. Jump Game V

题目如下:

Given an array of integers arr and an integer d. In one step you can jump from index i to index:

  • i + x where: i + x < arr.length and 0 < x <= d.
  • i - x where: i - x >= 0 and 0 < x <= d.

In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).

You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
Output: 4
Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.

Example 2:

Input: arr = [3,3,3,3,3], d = 3
Output: 1
Explanation: You can start at any index. You always cannot jump to any index.

Example 3:

Input: arr = [7,6,5,4,3,2,1], d = 1
Output: 7
Explanation: Start at index 0. You can visit all the indicies. 

Example 4:

Input: arr = [7,1,7,1,7,1], d = 2
Output: 2

Example 5:

Input: arr = [66], d = 1
Output: 1

Constraints:

  • 1 <= arr.length <= 1000
  • 1 <= arr[i] <= 10^5
  • 1 <= d <= arr.length

解题思路:本题可以逆向思维,假设只能从低处往高处跳,记dp[i] 为从起点开始,可以跳到i时最大跳跃的次数。那么如果i可以跳到j,有dp[j] = max(dp[j], dp[i] + 1) ,有了状态转移方程,接下来就只要按方块从低到高的顺序进行计算即可。

代码如下:

class Solution(object):
    def maxJumps(self, arr, d):
        """
        :type arr: List[int]
        :type d: int
        :rtype: int
        """
        dp = [1] * len(arr)
        
        couple = []
        for i in range(len(arr)):
            couple.append((i,arr[i]))
        
        def cmpf(i1,i2):
            return i1[1] - i2[1]
        
        couple.sort(cmp=cmpf)
        
        #dp[couple[0][0]] = 1
        
        res = 1
        
        #print couple
        
        for i in range(1,len(couple)):
            inx = couple[i][0]
            for j in range(inx-1,max(-1,inx-d-1),-1):
                if arr[inx] <= arr[j]:
                    break
                dp[inx] = max(dp[inx], dp[j] + 1)
                res = max(res,dp[inx])
            
            for j in range(inx+1,min(len(couple),inx+d+1)):
                if arr[inx] <= arr[j]:
                    break
                dp[inx] = max(dp[inx], dp[j] + 1)
                res = max(res,dp[inx])        
        #print dp
        return res
原文地址:https://www.cnblogs.com/seyjs/p/12283405.html