美文网首页
LeetCode之Maximum Width Ramp(Kotl

LeetCode之Maximum Width Ramp(Kotl

作者: 糕冷羊 | 来源:发表于2020-06-30 20:36 被阅读0次

    问题:



    方法:
    可以先对数组进行排序得到对应的indices数组,这时数组对应元素是单调递增的,当前index的最大宽度只与前面的最小index有关,因为后面的元素都比自己大不能形成坡,前面的元素都比自己大都可以形成坡,所以当前index减最小index即为最大宽度。

    class MaximumWidthRamp {
        fun maxWidthRamp(A: IntArray): Int {
            val indices = A.indices.sortedBy { A[it] }
            var width = 0
            var minIndex = A.lastIndex
            for (index in indices) {
                width = maxOf(width, index - minIndex)
                minIndex = minOf(index, minIndex)
            }
            return width
        }
    }
    
    fun main(args: Array<String>) {
        val input = intArrayOf(6, 0, 8, 2, 1, 5)
        val maximumWidthRamp = MaximumWidthRamp()
        print(maximumWidthRamp.maxWidthRamp(input))
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Maximum Width Ramp(Kotl

          本文链接:https://www.haomeiwen.com/subject/nfrfqktx.html