Algorithm/NeetCode

Divide Array Into Arrays With Max Difference

Tony Lim 2024. 11. 24. 15:24
728x90

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

class Solution:
    def divideArray(self, nums: List[int], k: int) -> List[List[int]]:
        nums.sort()
        res = []
        
        for i in range(0, len(nums), 3):
            if nums[i + 2] -nums[i] > k:
                return []
            res.append(nums[i: i+3])
        return res

by sorting nums we can have the least difference in each subarray.

we check if every subarray matches criteria k

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

Sort Characters By Frequency  (0) 2024.11.26
Sequential Digits  (0) 2024.11.25
Minimum Number of Operations to Make Array Empty  (0) 2024.11.23
Convert an Array Into a 2D Array With Conditions  (0) 2024.11.22
Design a Food Rating System  (0) 2024.11.21