Split Array With Minimum Difference Problem
Description
LeetCode Problem 3698.
You are given an integer array nums.
Split the array into exactly two subarrays, left and right, such that left is strictly increasing and right is strictly decreasing.
Return the minimum possible absolute difference between the sums of left and right. If no valid split exists, return -1.
Example 1:
Input: nums = [1,3,2]
Output: 2
Explanation:
i left right Validity left sum right sum Absolute difference
0 [1] [3, 2] Yes 1 5 |1 - 5| = 4
1 [1, 3] [2] Yes 4 2 |4 - 2| = 2
Thus, the minimum absolute difference is 2.
Example 2:
Input: nums = [1,2,4,3]
Output: 4
Explanation:
i left right Validity left sum right sum Absolute difference
0 [1] [2, 4, 3] No 1 9 -
1 [1, 2] [4, 3] Yes 3 7 |3 - 7| = 4
2 [1, 2, 4] [3] Yes 7 3 |7 - 3| = 4
Thus, the minimum absolute difference is 4.
Example 3:
Input: nums = [3,1,2]
Output: -1
Explanation:
No valid split exists, so the answer is -1.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Prefix Sum + Two Arrays to Record Monotonicity
We use a prefix sum array s to record the prefix sum of the array, where s[i] represents the sum of the array [0,..i]. Then we use two boolean arrays f and g to record the monotonicity of prefixes and suffixes respectively, where f[i] indicates whether the array [0,..i] is strictly increasing, and g[i] indicates whether the array [i,..n-1] is strictly decreasing.
Finally, we traverse array positions i where 0 <= i < n-1. If both f[i] and g[i+1] are true, then we can calculate the sums of left and right, which are s[i] and s[n-1]-s[i] respectively, and update the answer.
Complexity: The time complexity is O(n), and the space complexity is O(n), where n is the length of the array.
from itertools import accumulate
from math import inf
class Solution:
def splitArray(self, nums: List[int]) -> int:
s = list(accumulate(nums))
n = len(nums)
f = [True] * n
for i in range(1, n):
f[i] = f[i - 1]
if nums[i] <= nums[i - 1]:
f[i] = False
g = [True] * n
for i in range(n - 2, -1, -1):
g[i] = g[i + 1]
if nums[i] <= nums[i + 1]:
g[i] = False
ans = inf
for i in range(n - 1):
if f[i] and g[i + 1]:
s1 = s[i]
s2 = s[n - 1] - s[i]
ans = min(ans, abs(s1 - s2))
return ans if ans < inf else -1