본문 바로가기

LeetCode

2966. Divide Array Into Arrays With Max Difference

You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k.

Divide the array nums into n / 3 arrays of size 3 satisfying the following condition:

  • The difference between any two elements in one array is less than or equal to k.

Return a 2D array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them.

 

Example 1:

Input: nums = [1,3,4,8,7,9,3,5,1], k = 2

Output: [[1,1,3],[3,4,5],[7,8,9]]

Explanation:

The difference between any two elements in each array is less than or equal to 2.

Example 2:

Input: nums = [2,4,2,2,5,2], k = 2

Output: []

Explanation:

Different ways to divide nums into 2 arrays of size 3 are:

  • [[2,2,2],[2,4,5]] (and its permutations)
  • [[2,2,4],[2,2,5]] (and its permutations)

Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since 5 - 2 = 3 > k, the condition is not satisfied and so there is no valid division.

Example 3:

Input: nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14

Output: [[2,2,12],[4,8,5],[5,9,7],[7,8,5],[5,9,10],[11,12,2]]

Explanation:

The difference between any two elements in each array is less than or equal to 14. 

 

출처 : https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/description/

 

 

풀이 

 

function divideArray(nums: number[], k: number): number[][] {
    nums.sort((a,b) => a-b)
    let answer = []
    for(let i = 2 ; i < nums.length; i = i+3){
        if((nums[i] - nums[i-2]) <= k){
            let arr = nums.slice(i-2,i+1)
            answer.push(arr)
        }else{
            return []
        }

    }
    return answer
    
};

 

주어진 배열 nums를 정렬하고, 특정 조건에 따라 작은 배열들로 나누는 함수

  • 먼저 입력받은 배열 nums를 오름차순으로 정렬
  • 결과를 담을 빈 배열 answer를 초기화
  • 인덱스 i를 2부터 시작하여 배열의 끝까지 반복, 3씩 증가
  • nums[i]와 nums[i-2]의 차이가 k 이하인지 확인
    • 조건을 만족하면 nums.slice(i-2, i+1)로 세 개의 원소를 잘라내어 arr에 저장하고, 이를 answer 배열에 추가
    • 조건을 만족하지 않으면 빈 배열 []을 반환하며 함수 실행을 종료
    • 반복문을 모두 완료하면 최종적으로 나눠진 배열들을 담고 있는 answer를 반환

 

예시

  • 입력: nums = [1, 3, 5, 7, 9, 11], k = 4
  • 동작 과정:
    1. 배열 정렬: [1, 3, 5, 7, 9, 11] (이미 정렬된 상태)
    2. 첫 번째 반복:
      • i = 2: nums[2] - nums[0] = 5 - 1 = 4 (조건 만족)
      • arr = [1, 3, 5] → answer = [[1, 3, 5]]
    3. 두 번째 반복:
      • i = 5: nums[5] - nums[3] = 11 - 7 = 4 (조건 만족)
      • arr = [7, 9, 11] → answer = [[1, 3, 5], [7, 9, 11]]
    4. 반복 종료 및 결과 반환: [[1, 3, 5], [7, 9, 11]]