Maximum Score of a Split Problem
#3788
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3788.
You are given an integer array nums of length n.
Choose an index i such that 0 <= i < n - 1.
For a chosen split index i:
- Let
prefixSum(i)be the sum ofnums[0] + nums[1] + ... + nums[i]. - Let
suffixMin(i)be the minimum value amongnums[i + 1], nums[i + 2], ..., nums[n - 1].
The score of a split at index i is defined as:
score(i) = prefixSum(i) - suffixMin(i)
Return an integer denoting the maximum score over all valid split indices.
Example 1:
Input: nums = [10,-1,3,-4,-5]
Output: 17
Explanation:
The optimal split is at i = 2, score(2) = prefixSum(2) - suffixMin(2) = (10 + (-1) + 3) - (-5) = 17.
Example 2:
Input: nums = [-7,-5,3]
Output: -2
Explanation:
The optimal split is at i = 0, score(0) = prefixSum(0) - suffixMin(0) = (-7) - (-5) = -2.
Example 3:
Input: nums = [1,1]
Output: 0
Explanation:
The only valid split is at i = 0, score(0) = prefixSum(0) - suffixMin(0) = 1 - 1 = 0.
Constraints:
2 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Prefix Sum and Suffix Minimum
For a split at i we need the sum of nums[0..i] and the minimum of nums[i+1..]. Both can be prepared in one pass each.
- Build
suf[i], the minimum ofnums[i..n-1], by scanning from the right. - Scan
ifrom0ton - 2, keeping the running prefix sumpre. The score of the split ispre - suf[i + 1]. - Return the largest score.
The sums reach about 1014, so use 64-bit integers.
Complexity: O(n) time and O(n) extra space.
from math import inf
class Solution:
def maximumScore(self, nums: List[int]) -> int:
n = len(nums)
suf = [nums[-1]] * n
for i in range(n - 2, -1, -1):
suf[i] = min(nums[i], suf[i + 1])
ans = -inf
pre = 0
for i in range(n - 1):
pre += nums[i]
ans = max(ans, pre - suf[i + 1])
return ans