Rearrange Array to Keep Every Subarray Sum Bounded
You are given an integer array nums of size n such that the sum of all elements is 0.
You need to rearrange the elements of nums so that in the new arrangement, the absolute sum of every contiguous subarray is strictly smaller than: maximum element of nums - minimum element of nums
Return any valid rearranged array that satisfies this condition.
If multiple valid answers exist, return any one of them.
Your answer will be checked by a special validator, so you do not need to match one fixed output.
If no valid arrangement exists, return an empty array.
Notes
- Return the rearranged array directly, not the indices.
- A subarray means a contiguous part of the rearranged array.
- The checker will validate whether your returned array is correct.
- If more than one valid rearrangement is possible, any one of them will be accepted.
Example 1:
Input: nums = [3, -2, -1]
Output: [-2, 3, -1]
Explanation:
The maximum absolute subarray sum in this arrangement is 3.
Also, max(nums) - min(nums) = 3 - (-2) = 5.
Since 3 < 5, this arrangement is valid.
Example 2:
Input: nums = [4, -3, -1, 0]
Output: [-3, 4, -1, 0]
Explanation:
The maximum absolute subarray sum here is 4.
Also, max(nums) - min(nums) = 4 - (-3) = 7.
Since 4 < 7, this output is valid.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [2, -2, 1, -1]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 300000
- -109 <= nums[i] <= 109
- Sum of all elements in nums is 0