|
| 1 | +namespace LeetCodeNet.Medium.Array |
| 2 | +{ |
| 3 | + /// <summary> |
| 4 | + /// https://leetcode.com/problems/find-the-value-of-the-partition/ |
| 5 | + /// </summary> |
| 6 | + /// <remarks> |
| 7 | + /// You are given a positive integer array nums. |
| 8 | + /// Partition nums into two arrays, nums1 and nums2, such that: |
| 9 | + /// Each element of the array nums belongs to either the array nums1 or the array nums2. |
| 10 | + /// Both arrays are non-empty. |
| 11 | + /// The value of the partition is minimized. |
| 12 | + /// The value of the partition is |max(nums1) - min(nums2)|. |
| 13 | + /// Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2. |
| 14 | + /// Return the integer denoting the value of such partition. |
| 15 | + /// </remarks> |
| 16 | + internal sealed class FindtheValueofthePartition_2740 |
| 17 | + { |
| 18 | + /// <summary> |
| 19 | + /// The partition will be minimized when the two consecutive elements in the source array have the minimum difference. |
| 20 | + /// This division will result in the first sub-array having the maximum value, and the following element will be the minimum of the next sub-array. |
| 21 | + /// To apply this approach, we need to sort the source array first and then successively check two elements to find the minimum difference. |
| 22 | + /// </summary> |
| 23 | + /// <param name="nums"> Input data </param> |
| 24 | + /// <returns> Min. number partition </returns> |
| 25 | + /// <remarks> |
| 26 | + /// Time complexity: O(n * log(n)) |
| 27 | + /// Space complexity: O(1) |
| 28 | + /// </remarks> |
| 29 | + public int MinPartitionValue(int[] nums) |
| 30 | + { |
| 31 | + System.Array.Sort(nums); |
| 32 | + |
| 33 | + var minValue = int.MaxValue; |
| 34 | + |
| 35 | + for (var i = 1; i < nums.Length; i++) |
| 36 | + { |
| 37 | + minValue = Math.Min(Math.Abs(nums[i] - nums[i - 1]), minValue); |
| 38 | + } |
| 39 | + |
| 40 | + return minValue; |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments