题目如下:

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

最新文章

  1. 【转】Xen与XenServer的区别
  2. 破解myEclipse
  3. Oracle连接与会话
  4. Mac OSX网络诊断命令
  5. 下一代Asp.net开发规范OWIN(2)—— Katana介绍以及使用
  6. 编译安装zabbix 3.0及分开部署配置详解
  7. 做一些Spring AOP做过的事,封装 jdk动态代理成为一个黑盒子
  8. linux下proc目录详解
  9. C# JackLib系列之Form窗体的ShowWithoutActivation属性及其作用
  10. Rabin-Miller算法
  11. 【转】iOS开发系列--数据存取
  12. 自定义checkbox样式
  13. 性能优化工具---vmstat
  14. Xamarin.Android开发实践(三)
  15. iOS开发一些小技巧
  16. 探讨.NET Core数据加密和解密问题
  17. SQL SERVER查看索引使用情况
  18. 聚币网API[Python2版]
  19. Opencv 330 如何裁剪图片中大的目标?
  20. UVA850【简单模拟】

热门文章

  1. 攻防世界 | hello_pwn
  2. java 中异常类
  3. keras:InternalError: Failed to create session
  4. thread_process_action
  5. iOS无限后台加速耗电的问题
  6. STM32 ADC基础与多通道采样
  7. sql查询XML
  8. Java常用工具——java包装类
  9. Aliyun mysql配置 远程访问 10038
  10. WPF属性之理解附加属性