Leetcode 1021. Best Sightseeing Pair.

本文介绍了一种求解两个景点间最大配对得分的算法。通过重构数组和动态更新最大值的方法,有效地解决了这一问题。提供了两种高效实现方案,并附带详细代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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 :

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

Nodes :

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

Code

1.A[i] + A[j] + i - j = A[i] + i + A[j] - j。所以可以重新构建两个数组,分别存储A[i]+i和A[i]-i.然后计算这两个数组中元素之和的最大值。(传送门)

class Solution {
    public int maxScoreSightseeingPair(int[] A) {
        if (A == null || A.length <= 1) return 0;
        int[] plus = new int[A.length];
        int[] minus = new int[A.length];
        for (int i = 0; i < A.length; i++) {
            plus[i] = A[i] + i;
            minus[i] = A[i] - i;
        }
        int p = plus[0];
        int m = minus[1];
        int res = Integer.MIN_VALUE;
        for (int i = 1; i < A.length; i++) {
            // now we search max minus from index i
            m = Math.max(m, minus[i]);
            res = Math.max(res, p + m);
            if (plus[i] > p) {
                p = plus[i];
                m = Integer.MIN_VALUE;
                continue;
            }
        }
        return res;
    }
}

改进一下:记录之前最大A[i]+i的id(传送门)

public int maxScoreSightseeingPair(int[] A) {
    int ans =A[0];
    int prevBestIdx =0;
    for(int j=1;j<A.length;j++){
        ans = Math.max(ans, A[prevBestIdx]+prevBestIdx+A[j]-j);
        if(A[prevBestIdx ]+prevBestIdx <A[j]+j){
            prevBestIdx =j;
        }
    }
    return ans;
}

2.下面这个思路太厉害了。还是先看代码(传送门):

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;
}

解释一下,cur这个变量记录的是之前最大值减去到当前的位置。你每往前走一步,那么相当于最大值的value减去1,然后在加上当前的value,与记录的最大值比较,即得答案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值