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 nums belongs to either the array nums1 or the array nums2.
  • 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
Find the Value of the Partition1324Step 1: Input array [1,3,2,4]1234Step 2: Sort to [1,2,3,4] and check consecutive pairsResult: 1Minimum |max(nums1) - min(nums2)| = 1
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
Asked in
Google 15 Microsoft 12 Amazon 8
22.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen