[LeetCode] Best Sightseeing Pair

该博客介绍了一个寻找给定景点值数组中最佳观光组合的问题。算法工程师提出了一种解决方案,通过数学优化找到最大得分对。代码实现中,使用了动态规划策略,遍历数组并维护前缀最大值,最终返回最大得分。时间复杂度为O(n),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

Description

Best Sightseeing Pair: You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

The score of a pair (i < j) of sightseeing spots is values[i] + values[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:

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

Solution

The basic way is to use mathematics.

According to the description: The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j, and our goal it to maximize the score.

Then, we modify this formula: values[i] + values[j] + i - j = (values[j] - j) + (values[i] + i).

So, the only thing for us is to find an anwser: (values[j] - j) + max(values[i] + i), where i < j.

Code

class Solution {
public:
    int maxScoreSightseeingPair(vector<int>& values) {
        int n = values.size(), prev = values[0] + 0, ans = 0;
        for(int i = 1; i < n; i++) {
            ans = max(ans, prev + values[i] - i);
            prev = max(prev, values[i] + i);
        }
        return ans;
    }
};

Complexity

Time complexity: O(n)

Space complexity: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值