Maximum Sum Score of Array Problem
#2219
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 2219.
You are given a 0-indexed integer array nums of length n.
The sum score of nums at an index i where 0 <= i < n is the maximum of:
- The sum of the first
i + 1elements ofnums. - The sum of the last
n - ielements ofnums.
Return the maximum sum score of nums at any index.
Example 1:
Input: nums = [4,3,-2,5]
Output: 10
Explanation:
The sum score at index 0 is max(4, 4 + 3 + -2 + 5) = max(4, 10) = 10.
The sum score at index 1 is max(4 + 3, 3 + -2 + 5) = max(7, 6) = 7.
The sum score at index 2 is max(4 + 3 + -2, -2 + 5) = max(5, 3) = 5.
The sum score at index 3 is max(4 + 3 + -2 + 5, 5) = max(10, 5) = 10.
The maximum sum score of nums is 10.
Example 2:
Input: nums = [-3,-5]
Output: -3
Explanation:
The sum score at index 0 is max(-3, -3 + -5) = max(-3, -8) = -3.
The sum score at index 1 is max(-3 + -5, -5) = max(-8, -5) = -5.
The maximum sum score of nums is -3.
Constraints:
n == nums.length1 <= n <= 10^5-10^5 <= nums[i] <= 10^5
Solution
Approach: Prefix Sums
The sum score at index i is the larger of the prefix sum up to i and the suffix sum from i. Keep a running prefix sum l (starting at 0) and a suffix sum r (starting at the total). For each element x, add it to l, record max(l, r) into the answer, then subtract x from r so it becomes the suffix starting at the next index.
Complexity: O(n) time and O(1) extra space.
from math import inf
class Solution:
def maximumSumScore(self, nums: List[int]) -> int:
l, r = 0, sum(nums)
ans = -inf
for x in nums:
l += x
ans = max(ans, l, r)
r -= x
return ans