[LeetCode] Find the Value of the Partition

2740. Find the Value of the Partition

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.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int findValueOfPartition(vector<int>& A) {
sort(begin(A), end(A));
int res = INT_MAX;
for(int i = 0; i < A.size() - 1; i++) res = min(res, A[i+1] - A[i]);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/18/PS/LeetCode/find-the-value-of-the-partition/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.