|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2966. Divide Array Into Arrays With Max Difference |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/divide-array-into-arrays-with-max-difference |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given an integer array nums of size n and a positive integer k. |
| 9 | +Divide the array into one or more arrays of size 3 satisfying the following conditions: |
| 10 | +* Each element of nums should be in exactly one array. |
| 11 | +* The difference between any two elements in one array is less than or equal to k. |
| 12 | +Return a 2D array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: nums = [1,3,4,8,7,9,3,5,1], k = 2 |
| 16 | +Output: [[1,1,3],[3,4,5],[7,8,9]] |
| 17 | +Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9]. |
| 18 | +The difference between any two elements in each array is less than or equal to 2. |
| 19 | +Note that the order of elements is not important. |
| 20 | +
|
| 21 | +Example 2: |
| 22 | +Input: nums = [1,3,3,2,7,3], k = 3 |
| 23 | +Output: [] |
| 24 | +Explanation: It is not possible to divide the array satisfying all the conditions. |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +* n == nums.length |
| 28 | +* 1 <= n <= 105 |
| 29 | +* n is a multiple of 3. |
| 30 | +* 1 <= nums[i] <= 105 |
| 31 | +* 1 <= k <= 105 |
| 32 | +=end |
| 33 | + |
| 34 | +# @param {Integer[]} nums |
| 35 | +# @param {Integer} k |
| 36 | +# @return {Integer[][]} |
| 37 | +def divide_array(nums, k) |
| 38 | + possible_array = [] |
| 39 | + nums.sort! |
| 40 | + nums.each_slice(3) do |n| |
| 41 | + return [] if n[2] - n[0] > k |
| 42 | + possible_array << n |
| 43 | + end |
| 44 | + possible_array |
| 45 | +end |
| 46 | + |
| 47 | +# **************** # |
| 48 | +# TEST # |
| 49 | +# **************** # |
| 50 | + |
| 51 | +require "test/unit" |
| 52 | +class Test_divide_array < Test::Unit::TestCase |
| 53 | + def test_ |
| 54 | + assert_equal [[1, 1, 3], [3, 4, 5], [7, 8, 9]], divide_array([1, 3, 4, 8, 7, 9, 3, 5, 1], 2) |
| 55 | + assert_equal [], divide_array([1, 3, 3, 2, 7, 3], 3) |
| 56 | + end |
| 57 | +end |
0 commit comments