zoukankan      html  css  js  c++  java
  • 【leetcode】1021. Best Sightseeing Pair

    题目如下:

    Given an array A of positive integers, A[i]represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.

    The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them.

    Return the maximum score of a pair of sightseeing spots.

    Example 1:

    Input: [8,1,5,2,6]
    Output: 11
    Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11
    

    Note:

    1. 2 <= A.length <= 50000
    2. 1 <= A[i] <= 1000

    解题思路:本题和【leetcode】123. Best Time to Buy and Sell Stock III 有点类似。题目要求求出A[i] + A[j] + i - j最大值,这个表达式可以等价变为 (A[i] + i ) + (A[j] - j),对于A中每一个元素来说,都对应着两个值,分别是A[i]+i和A[i]-i。本题的解法可以抽象成把A分成两部分,第一部分找出使得A[i]+i能得到最大值的i,第二部分找出A[j]-j能得到最大值的j,两者之和就是最终的结果。

    代码如下:

    class Solution(object):
        def maxScoreSightseeingPair(self, A):
            """
            :type A: List[int]
            :rtype: int
            """
            l_1 = [-float('inf')] * len(A)
            l_2 = [-float('inf')] * len(A)
            max_1 = -float('inf')
            max_2 = -float('inf')
            res = -float('inf')
            for i in range(len(A)-1):
                max_1 = max(i + A[i],max_1)
                l_1[i] = max_1
    
                max_2 = max(A[len(A) - 1-i] - (len(A) - 1-i),max_2)
                l_2[len(A) - 1-i] = max_2
    
                if i >= len(A) / 2 -1:
                    res = max(res,l_1[i] + l_2[i+1])
                    res = max(res,l_1[len(A) - 1-i-1] + l_2[len(A) - 1-i])
            #print l_1
            #print l_2
            return res
  • 相关阅读:
    冲刺五
    ubuntu安装utorrent
    struts2中properties属性
    Hadoop下的word count程序
    导入svn项目时eclipse崩溃
    Struts2 中jsp直接跳转到action
    用eclipse开发hadoop程序
    ubuntu下安装java
    【橙色警报】最新盗qq号方式,连我这个老鸟都一不小心被骗了
    在ubuntu上安装hadoop(书和官方文档结合的)
  • 原文地址:https://www.cnblogs.com/seyjs/p/10598358.html
Copyright © 2011-2022 走看看