1014. 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:

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

Rust Solution

struct Solution;

impl Solution {
    fn max_score_sightseeing_pair(a: Vec<i32>) -> i32 {
        let n = a.len();
        let mut maxs = vec![];
        let mut prev_max = 0;
        let mut res = 0;
        for i in 0..n {
            prev_max = prev_max.max(i as i32 + a[i]);
            maxs.push(prev_max);
        }
        for i in 1..n {
            res = res.max(maxs[i - 1] + a[i] - i as i32);
        }
        res
    }
}

#[test]
fn test() {
    let a = vec![8, 1, 5, 2, 6];
    let res = 11;
    assert_eq!(Solution::max_score_sightseeing_pair(a), res);
}

Having problems with this solution? Click here to submit an issue on github.