AlgoMaster Logo

1014. Best Sightseeing Pair

values=[8, 1, 5, 2, 6]
1public int maxScoreSightseeingPair(int[] values) {
2    // Initialize max_left with first element
3    int maxLeft = values[0] + 0;
4    int result = 0;
5
6    for (int j = 1; j < values.length; j++) {
7        // Calculate score using decomposed formula
8        // score = (values[i] + i) + (values[j] - j)
9        int rightComponent = values[j] - j;
10        int score = maxLeft + rightComponent;
11
12        // Update result if better score found
13        result = Math.max(result, score);
14
15        // Update max_left for next iteration
16        // maxLeft represents max(values[i] + i) for all i < j
17        int leftComponent = values[j] + j;
18        maxLeft = Math.max(maxLeft, leftComponent);
19    }
20
21    return result;
22}
0 / 26
8152601234