Reason About an Endpoint-Only Interval Score
GoogleSoftware Engineer · OnsiteLast updated
This problem tests the understanding of interval arithmetic properties and algorithmic implementation of selection logic in the presence of tied boundary indices.
Problem Statement
Consider an interval defined by two indices [start, end] in a zero-indexed array A of length N. Let the "score" of this interval be defined as the sum of elements from index start to end inclusive, minus the sum of elements in the strictly interior range (start, end).
- Mathematically demonstrate why this score is equivalent to
A[start] + A[end]ifstart < end, and explain the behavior whenstart == end. - Implement a function
calculate_interval_score(A, start, end)that returns this value. - Given an array
A, implement a functionfind_max_score_interval(A)that returns the maximum possible score for any valid interval0 <= start <= end < N. If multiple intervals yield the same maximum score, return the interval that minimizes thestartindex, then minimizes theendindex.
Examples
# Example 1
A = [1, 5, 2, 8, 3]
# For interval [1, 3]: A[1..3] = [5, 2, 8]. Interior = [2].
# Score = (5+2+8) - (2) = 13.
# Equivalent to A[1] + A[3] = 5 + 8 = 13.
# Example 2
A = [10, -2, 10]
# For interval [0, 2]: A[0..2] = [10, -2, 10]. Interior = [-2].
# Score = (10 - 2 + 10) - (-2) = 18.
# Equivalent to A[0] + A[2] = 10 + 10 = 20... Wait, ensure the logic handles negatives.
Constraints
1 <= N <= 10^5-10^6 <= A[i] <= 10^6
Edge Cases
start == end: The interior is empty (sum = 0), so the score should beA[start].- Single element arrays.
Hints
Hint 1
Write out the sum of the interval: A[start] + A[start+1] + ... + A[end].
Hint 2
Subtract the interior sum A[start+1] + ... + A[end-1] from the total sum; notice the middle terms cancel out.
Hint 3
For the max score problem, you are simply looking for the maximum of (A[i] + A[j] where i < j) and (A[i] where i = j).
Follow-up questions
- How does the time complexity change if we require the interior to contain at least one element?
- If the array elements were strictly positive, how would that simplify finding the maximum score?
- How would you adapt the solution if the array was provided as a stream and you could only store a constant amount of memory?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.