其他分享
首页 > 其他分享> > leetcode: Maximum Width Ramp

leetcode: Maximum Width Ramp

作者:互联网

Problem

Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. The width of such a ramp is j - i.

Find the maximum width of a ramp in A. If one doesn’t exist, return 0.
Example:

Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: 
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.

Solution

首先将数列A和值和索引按值排序,排序之后再按顺序遍历A的索引。
注意,此时每个索引所对应的值一定都大于等于之前索引所对应的值。
所以只需要找索引的最大差就行了。

class Solution:
    def maxWidthRamp(self, A: List[int]) -> int:
        for i,a in enumerate(A):
            A[i] = (a,i)
        A = sorted(A)
        mark = len(A)-1
        ans = 0
        
        for _,i in A:
            ans = max(ans,i-mark)
            mark = min(i,mark)
        return ans

标签:return,索引,ramp,Ramp,mark,Width,width,ans,leetcode
来源: https://blog.csdn.net/qq184861643/article/details/87905571