Find the Value of the Partition - Problem
You are given a positive integer array nums.
Partition nums into two arrays, nums1 and nums2, such that:
- Each element of the array
numsbelongs to either the arraynums1or the arraynums2. - Both arrays are non-empty.
- The value of the partition is minimized.
The value of the partition is |max(nums1) - min(nums2)|.
Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2.
Return the integer denoting the value of such partition.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,2,4]
›
Output:
1
💡 Note:
Sort to get [1,2,3,4]. Best partition is [1] and [2,3,4] giving |1-2| = 1, or [1,2] and [3,4] giving |2-3| = 1.
Example 2 — All Same Elements
$
Input:
nums = [100,1,10]
›
Output:
9
💡 Note:
Sort to get [1,10,100]. Check splits: |1-10| = 9, |10-100| = 90. Minimum is 9.
Example 3 — Two Elements
$
Input:
nums = [1,1]
›
Output:
0
💡 Note:
Only one way to partition: nums1=[1], nums2=[1]. Value is |1-1| = 0.
Constraints
- 2 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,3,2,4] needs to be partitioned into two non-empty parts
2
Process
Sort array and find minimum difference between consecutive elements
3
Output
Return the minimum partition value
Key Takeaway
🎯 Key Insight: The optimal partition always occurs between consecutive elements in the sorted array
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code