[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

解題思路

維護兩個狀態(tài)轉移方程:

  • 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;
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網事_79a3閱讀 12,992評論 3 20
  • 我,平平凡凡,庸庸碌碌,看上去不配擁有出眾的故事;被生活撮成一堆,甚至不能擁有幾許不同。然而,你的這句“你一直都是...
    吃貨霞閱讀 315評論 0 0
  • 忘了是從什么時候開始喜歡張杰,亦不記得為什么喜歡他。但喜歡就是喜歡啊,哪有那么多為什么!就像你不止一次問我為什么喜...
    努力長肉肉的小五閱讀 431評論 0 0
  • 喜歡坐在窗邊的位置,看窗外的風景列隊倒退;喜歡聽憂傷的歌曲,品味歌詞中透漏的淡淡哀愁;喜歡隨著音樂放空自己,任思緒...
    青色日記1988閱讀 495評論 0 0

友情鏈接更多精彩內容