1014. Best Sightseeing Pair(Leetcode每日一題-2020.06.17)

Problem

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.

Example1

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

Solution

在這裏插入圖片描述

class Solution {
public:
    int maxScoreSightseeingPair(vector<int>& A) {
        if(A.empty())
            return 0;
        
        int ret = 0;
        int maxI = A[0] + 0;
        for(int j = 1;j<A.size();++j)
        {
            ret = max(ret,A[j]-j + maxI);
            maxI = max(A[j] + j,maxI);
        }

        return ret;

    }
};

Ref

https://leetcode-cn.com/problems/best-sightseeing-pair/solution/c-cong-on2you-hua-dao-guan-fang-ti-jie-onde-guo-ch/

https://leetcode-cn.com/problems/best-sightseeing-pair/solution/zui-qing-chu-de-dptui-dao-guo-cheng-by-feichaix/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章