The "Best Sightseeing Pair interview question" is an optimization problem involving an array of "values" for different locations. A pair of locations with has a score defined as values[i] + values[j] + i - j. This formula accounts for the beauty of both spots (values[i] + values[j]) but penalizes the score based on the distance between them (j - i). You need to find the maximum possible score.
Meta and Amazon ask the "Best Sightseeing Pair coding problem" to evaluate a candidate's ability to rewrite an objective function to enable a single-pass solution. It’s a classic example of how to turn an brute force into an linear scan. It tests "Dynamic Programming" and "Array interview pattern" skills.
This problem uses Function Decomposition and Linear Scanning.
The formula values[i] + values[j] + i - j can be split into two parts:
values[i] + ivalues[j] - j
As you iterate through the array at index , you want to find the largest values[i] + i encountered so far (where ).max_left representing the best values[i] + i.max_score = max(max_score, max_left + values[j] - j).max_left for the next iteration: max_left = max(max_left, values[j] + j).Values: [8, 1, 5, 2]
max_left = .max_left = .max_left = .values[i] and then subtracting distance later, which doesn't account for the fact that a slightly smaller values[i] that is closer to might be better.max_left after calculating the score for the current (ensures ).Whenever you see a formula like A[i] + A[j] + (some relationship between i and j), try to group the terms so that each part depends on only one variable. This is the key to converting many "pair" problems into linear "running maximum" problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Length of Valid Subsequence I | Medium | Solve | |
| Maximum Absolute Sum of Any Subarray | Medium | Solve | |
| Maximum Alternating Subsequence Sum | Medium | Solve | |
| Solving Questions With Brainpower | Medium | Solve | |
| Find the Maximum Length of Valid Subsequence II | Medium | Solve |