FastPrepMaximize Two Endpoint Values

Maximize Two Endpoint Values

Google logoGoogle● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

You are given an integer array values. Choose two indices i and j with i < j.

The score of the chosen pair is

sum(values[i..j]) - sum(values[i+1..j-1]),

where the sum of an empty interior range is 0.

Return the maximum score over all valid pairs. The result is a 64-bit integer.

Function

maximumEndpointSum(values: int[]) → long

Examples

Example 1

values = [4,1,7,3]return = 11

Choose the endpoints with values 4 and 7. Interior values cancel from the two range sums, so the score is 4 + 7 = 11.

Example 2

values = [-5,-2,-8]return = -7

The two largest values are -2 and -5, producing the maximum score -7.

Example 3

values = [6,6]return = 12

The only pair has no interior values and scores 6 + 6 = 12.

Constraints

  • 2 <= values.length <= 2 * 10^5
  • -10^9 <= values[i] <= 10^9

More Google problems

See Google hiring insights
public long maximumEndpointSum(int[] values) {
    // Write your code here.
}
values[4,1,7,3]
expected11
Checking account…