#3788
Maximum Score of a Split
MediumArrayPrefix SumPrefix SumSuffix Array
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Precompute prefix sums and suffix minimums to efficiently calculate scores in a single pass, reducing time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum array where prefix[i] = sum of nums[0] to nums[i].
- 2Step 2: Create a suffix min array where suffix[i] = min of nums[i] to nums[n-1].
- 3Step 3: Iterate through valid split indices to compute scores using precomputed arrays and track the maximum score.
solution.py14 lines
1def maxScore(nums):
2 n = len(nums)
3 prefix = [0] * n
4 suffix = [0] * n
5 prefix[0] = nums[0]
6 for i in range(1, n):
7 prefix[i] = prefix[i - 1] + nums[i]
8 suffix[n - 1] = nums[n - 1]
9 for i in range(n - 2, -1, -1):
10 suffix[i] = min(suffix[i + 1], nums[i])
11 max_score = float('-inf')
12 for i in range(n - 1):
13 max_score = max(max_score, prefix[i] - suffix[i + 1])
14 return max_scoreℹ
Complexity note: The complexity is linear because we traverse the array a few times to build prefix and suffix arrays.
- 1Prefix sums help in quickly calculating cumulative values.
- 2Suffix minimums allow efficient retrieval of minimum values after a split.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.