[LeetCode] 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:

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

解题思路

维护两个状态转移方程:

  • res = max(res, cur+a)
  • cur = max(cur, a) - 1

cur表示曾经遇到过的最大得分,但是它每走一步都会衰减1,res当前到当前的最大得分。

实现代码

// Runtime: 4 ms, faster than 67.70% of Java online submissions for Best Sightseeing Pair.
// Memory Usage: 50.3 MB, less than 100.00% of Java online submissions for Best Sightseeing Pair.
class Solution {
    public int maxScoreSightseeingPair(int[] A) {
        int res = 0, cur = 0;
        for (int a : A) {
            res = Math.max(res, cur + a);
            cur = Math.max(cur, a) - 1;
        }
        return res;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,297评论 3 20
  • 我,平平凡凡,庸庸碌碌,看上去不配拥有出众的故事;被生活撮成一堆,甚至不能拥有几许不同。然而,你的这句“你一直都是...
    吃货霞阅读 299评论 0 0
  • 忘了是从什么时候开始喜欢张杰,亦不记得为什么喜欢他。但喜欢就是喜欢啊,哪有那么多为什么!就像你不止一次问我为什么喜...
    努力长肉肉的小五阅读 389评论 0 0
  • 喜欢坐在窗边的位置,看窗外的风景列队倒退;喜欢听忧伤的歌曲,品味歌词中透漏的淡淡哀愁;喜欢随着音乐放空自己,任思绪...
    青色日记1988阅读 444评论 0 0